Beispiel #1
0
def get_info(container):
    channel = get_channel(container)
    macaroon = codecs.encode(open(_macaroon(container), 'rb').read(), 'hex')
    stub = lnrpc.LightningStub(channel)
    request = ln.GetInfoRequest()
    response = stub.GetInfo(request, metadata=[('macaroon', macaroon)])
    return response
Beispiel #2
0
 def ping(self):
     try:
         self.client.GetInfo(ln.GetInfoRequest())
         return True
     except Exception as e:
         logger.exception(e)
         return False
Beispiel #3
0
def get_info_dict(stub, macaroon):
    # Retrieve and display the wallet balance
    response = stub.GetInfo(ln.GetInfoRequest(),
                            metadata=[('macaroon', macaroon)])
    # responseWallet = stub.WalletBalance(ln.WalletBalanceRequest(),metadata = [('macaroon',macaroon)])

    return response
Beispiel #4
0
    def mainUI(self):
        self.screen.fill(background_color)
        self.add_qr_code()
        self.build_info_section("admin", get_ip(), (520, 120), False, True)
        # Tor is always going to be really long so not sure about this one ... :/
        self.build_info_section(
            "tor",
            "r7cckasdfasfdargsnf4eoxaivgiykmrcglhg4zlwueknhuw66otiid.onion",
            (columns_x[0], rows_y[0]), pygame.freetype.Font(bold_font, 22))

        stub = get_stub()
        metadata = [('macaroon', get_macaroon())]

        response = stub.GetInfo(ln.GetInfoRequest(), metadata=metadata)

        btcresponse = rpc_connection.getblockchaininfo()

        self.build_info_section("Max Send", "3M Sats",
                                (columns_x[0], rows_y[1]))
        self.build_info_section("Max Recieve", "2M Sats",
                                (columns_x[1], rows_y[1]))
        self.build_info_section("Active Channels", "16",
                                (columns_x[2], rows_y[1]))
        self.build_info_section("24H Forwards",
                                str(response.num_active_channels),
                                (columns_x[0], rows_y[2]))
        self.build_info_section(
            "Sync progress",
            str(btcresponse["verificationprogress"] * 100) + "%",
            (columns_x[1], rows_y[2]))

        pygame.display.set_caption("UmbrUI")
        pygame.display.update()

        self.loaded = True
Beispiel #5
0
def main():
    if not BOT_TOKEN:
        sys.stderr.write("Please specify BOT_TOKEN environment variable\n")
        return 1

    # Open database
    global sessionmaker
    logger.info("Opening database {}".format(DB_PATH))
    sessionmaker = db.open_database(DB_PATH)
    session = sessionmaker()
    logger.info("Counting {} users and {} transactions".format(
        db.count_users(session), db.count_transactions(session)))
    session.close()

    # Connect to lightning gRPC
    global stub
    logger.info("Reading TLS certificate {}".format(CERT_PATH))
    cert = open(CERT_PATH, 'rb').read()
    creds = grpc.ssl_channel_credentials(cert)
    logger.info("Connecting to lnd at {}".format(LND_GRPC))
    channel = grpc.secure_channel(LND_GRPC, creds)
    stub = lnrpc.LightningStub(channel)
    # Do a test call
    info = stub.GetInfo(ln.GetInfoRequest(), timeout=GRPC_TIMEOUT)
    logger.info(info)
    logger.info("Connected to lnd".format(info.alias))
    if not info.testnet and TESTNET:
        logger.critical("lnd is running on mainnet, quitting")
        sys.exit(1)
    if not info.synced_to_chain:
        logger.critical("lnd is not synced")
        sys.exit(1)
    if not info.chains == ["bitcoin"]:
        logger.critical("Only bitcoin is supported at this time")
        sys.exit(1)

    # Create the telegram bot
    global updater
    updater = Updater(token=BOT_TOKEN)
    updater.dispatcher.add_handler(CommandHandler('start', command_start))
    updater.dispatcher.add_handler(CommandHandler('balance', command_balance))
    updater.dispatcher.add_handler(
        CommandHandler('invoice', command_invoice, pass_args=True))
    updater.dispatcher.add_handler(
        CommandHandler('pay', command_pay, pass_args=True))
    updater.dispatcher.add_handler(CommandHandler('help', help_handler))
    updater.dispatcher.add_handler(MessageHandler(Filters.photo,
                                                  photo_handler))
    updater.dispatcher.add_handler(MessageHandler(Filters.text, text_handler))
    updater.start_polling()

    # Payments listener in a new thread
    import thread
    thread.start_new_thread(payments_listener_thread, ())

    logger.info("Bot started")

    # Wait until telegram poller stops or ^C
    updater.idle()
    return 0
Beispiel #6
0
def getInfo(stub, macaroon):
    # Retrieve and display the wallet balance
    response = stub.GetInfo(ln.GetInfoRequest(),
                            metadata=[('macaroon', macaroon)])
    response_wallet = stub.WalletBalance(ln.WalletBalanceRequest(),
                                         metadata=[('macaroon', macaroon)])

    network = "[Mainnet]"
    if response.testnet:
        network = "[Testnet]"

    descriptionStr = term_print("Alias: ", bcolors.OKGREEN) + term_print(
        response.alias, bcolors.BOLD) + "\t\t" + term_print(
            "Pubkey: ", bcolors.OKGREEN) + str(response.identity_pubkey) + "\n"
    statusStr = term_print("Channels:", bcolors.OKGREEN) + str(
        response.num_active_channels
    ) + "(" + str(response.num_pending_channels) + ")\t" + term_print(
        "Peers:",
        bcolors.OKGREEN) + str(response.num_peers) + "\t" + term_print(
            "Height:",
            bcolors.OKGREEN) + str(response.block_height) + "\t" + term_print(
                "Balance:", bcolors.OKGREEN) + str(
                    response_wallet.total_balance) + " (" + str(
                        response_wallet.confirmed_balance) + ":" + str(
                            response_wallet.unconfirmed_balance
                        ) + ") SAT\t" + term_print(network, bcolors.OKGREEN)

    return descriptionStr + statusStr
Beispiel #7
0
def check_lnd():
    try:
        stub = get_stub()
        metadata = [('macaroon',get_macaroon())]
        response = stub.GetInfo(ln.GetInfoRequest(),metadata=metadata)
        response.num_active_channels
    except grpc._channel._InactiveRpcError:
        sleep(2)
        check_lnd()
Beispiel #8
0
 def get_uri(self):
     try:
         request = ln.GetInfoRequest()
         response = self.stub.GetInfo(request)
         logging.info(response)
         node_id = response.identity_pubkey
         return "%s@%s:%d" % (node_id, self.node_address, self.node_port)
     except grpc.RpcError as e:
         logging.error(e)
         return e.details()
def index():

    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()
        onchain_balance = rpc_connect.getbalance() 
        bitcoin_version = (rpc_connect.getnetworkinfo()['subversion'])[1:-1].replace("Satoshi:","")
        sync_prog = str(round(rpc_connect.getblockchaininfo()['verificationprogress']*100, 2)) + "%"
        chain_type = rpc_connect.getblockchaininfo()['chain']
        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"
    except:
        current_block_height = onchain_peers = onchain_balance = bitcoin_version = sync_prog = chain_type = "Offline!"

    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)

        response = stub.GetInfo(ln.GetInfoRequest(), metadata=[('macaroon', macaroon)])
        satbalance = stub.ChannelBalance(ln.ChannelBalanceRequest(), metadata=[('macaroon', macaroon)])
        lightning_channels_act = response.num_active_channels
        lightning_peers = response.num_peers
        offchain_balance = u"ş " + str(format(satbalance.balance,','))
        lightning_version = response.version[:5]
        alias = response.alias
    except:

        lightning_channels_act = lightning_peers = offchain_balance = lightning_version = alias = "Offline!"


    return render_template('index.html', current_block_height=current_block_height,
         onchain_peers=onchain_peers, onchain_balance=onchain_balance, 
         bitcoin_version=bitcoin_version, sync_prog=sync_prog, chain_type=chain_type, lightning_channels_act=lightning_channels_act,
         lightning_peers=lightning_peers, offchain_balance=offchain_balance,
         lightning_version=lightning_version, alias=alias)
Beispiel #10
0
    def ping(self):
        """ Simple liveness test to see if the node is up and running

        Returns true if the node is reachable via RPC, false otherwise.
        """
        try:
            self.rpc.stub.GetInfo(lnrpc.GetInfoRequest())
            return True
        except Exception as e:
            print(e)
            return False
Beispiel #11
0
    def __init__(self, cert, config):
        cert_creds = grpc.ssl_channel_credentials(cert)
        auth_creds = grpc.metadata_call_credentials(metadata_callback)
        creds = grpc.composite_channel_credentials(cert_creds, auth_creds)

        channel = grpc.secure_channel(config.LND_HOST, creds)
        self.stub = lnrpc.LightningStub(channel)
        self.DEFAULT_PRICE = config.DEFAULT_PRICE
        self.DEFAULT_EXPIRY = config.DEFAULT_EXPIRY
        try:
            request = ln.GetInfoRequest()
            response = self.stub.GetInfo(request)
            logging.info(response)
        except grpc.RpcError as e:
            logging.error(e)
Beispiel #12
0
    def __init__(self, cert, config):
        creds = grpc.ssl_channel_credentials(cert)
        channel = grpc.secure_channel(config.LND_HOST, creds)
        self.stub = lnrpc.LightningStub(channel)
        self.DEFAULT_PRICE = config.DEFAULT_PRICE
        self.DEFAULT_EXPIRY = config.DEFAULT_EXPIRY
        try:
            request = ln.GetInfoRequest()
            response = self.stub.GetInfo(request)
            logging.info(response)
        except grpc.RpcError as e:
           logging.error(e)    

        self.broadcast = Broadcaster._instance
        self.invoiceThread = threading.Thread(target = self.subscribe_invoices)
        self.invoiceThread.daemon = True

        LndWrapper._instance = self
Beispiel #13
0
    async def initialize(self) -> None:
        """asynchronously init class and populate pubkey"""

        # TODO add wallet unlocking stub for wallet unlock
        # TODO max receive message length? = 1024^3
        i = 1
        while True:
            try:
                self.logger.info(f"Attempt ${i} to initialize lnd")
                self.stub = lnrpc.LightningStub(self._channel)
                req = ln.GetInfoRequest()
                info = await self.stub.GetInfo(req)
                self.id_pubkey = info.identity_pubkey
                assert self.id_pubkey
                self.logger.info("Success")
                break
            except (ConnectionRefusedError, gaierror) as error:
                i += 1
                self.logger.info(f"Attempt failed: {error}")
                await asyncio.sleep(5)
Beispiel #14
0
def get_header_line():

    # header
    response = stub.GetInfo(ln.GetInfoRequest(),
                            metadata=[('macaroon', macaroon)])
    alias = response.alias
    chain = response.chains[0]
    version = response.version

    header = "%s (%s, lnd %s)" % (alias, chain, version)

    request = ln.ListChannelsRequest(active_only=True)
    response = stub.ListChannels(request, metadata=[('macaroon', macaroon)])
    active_channels = response.channels

    request = ln.ListChannelsRequest(inactive_only=True)
    response = stub.ListChannels(request, metadata=[('macaroon', macaroon)])
    inactive_channels = response.channels

    header += "\n" + ("%d active channels and %d inactive channels" %
                      (len(active_channels), len(inactive_channels)))
    return header
Beispiel #15
0
def get_info():
    request = ln.GetInfoRequest()
    return stub.GetInfo(request, metadata=[('macaroon', macaroon)])
Beispiel #16
0
    nodeinfo = stub.GetNodeInfo(ln.NodeInfoRequest(pub_key=pubkey))
    if nodeinfo.node.addresses:
        return ".onion" in nodeinfo.node.addresses[0].addr
    else:
        return False


channel_options = [
    ("grpc.max_message_length", MESSAGE_SIZE_MB),
    ("grpc.max_receive_message_length", MESSAGE_SIZE_MB),
]

channel = grpc.secure_channel("localhost:10009", get_creds(), channel_options)
stub = lnrpc.LightningStub(channel)

identity_pubkey = stub.GetInfo(ln.GetInfoRequest()).identity_pubkey

lgraph = stub.DescribeGraph(ln.ChannelGraphRequest())
edges = lgraph.edges
nodes = lgraph.nodes

data = [(e.node1_pub, e.node2_pub, {"weight": e.capacity}) for e in edges]

json.dump(data, open("lightning_graph.json", "w"))


onions = [n.pub_key for n in nodes if is_onion(stub, n.pub_key)]
print(len(onions))

json.dump(onions, open("onions.json", "w"))
def getCurrentNodePubKey():
    request_getinfo = ln.GetInfoRequest()
    response_getinfo = stub.GetInfo(request_getinfo)
    return response_getinfo.identity_pubkey
Beispiel #18
0
async def r_info(*_) -> dict:
    request = ln.GetInfoRequest()
    return await LND.stub.GetInfo(request)
Beispiel #19
0
 def get_info(self):
     if self.info is None:
         self.info = self.stub.GetInfo(ln.GetInfoRequest())
     return self.info
Beispiel #20
0
 def getInfo(self):
     request = ln.GetInfoRequest()
     response = self.stub.GetInfo(request)
     return response
Beispiel #21
0
 def info(self):
     r = self.rpc.stub.GetInfo(lnrpc.GetInfoRequest())
     return {
         'id': r.identity_pubkey,
         'blockheight': r.block_height,
     }
Beispiel #22
0
#illustrating for alice (port 10001)
with open(
        os.path.expanduser(
            '~/snap/go/dev/alice/data/chain/bitcoin/simnet/admin.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)


# 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:10001',
    combined_creds)  #example uses 10009, but my user ports are 10001-3

#create the stub (some frameworks just call this the "client")
stub = lnrpc.LightningStub(channel)

print(stub.GetInfo(ln.GetInfoRequest()))
Beispiel #23
0
def getinfo():
	return stub.GetInfo(ln.GetInfoRequest())
Beispiel #24
0
 def GetInfo(self):
     response = stub.GetInfo(ln.GetInfoRequest())
     return response
Beispiel #25
0
from collections import defaultdict

macaroon = codecs.encode(open('/home/joao/.lnd/data/chain/bitcoin/mainnet/admin.macaroon', 'rb').read(), 'hex')
os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
cert = open('/home/joao/.lnd/tls.cert', 'rb').read()
ssl_creds = grpc.ssl_channel_credentials(cert)
channel = grpc.secure_channel('localhost:10009', ssl_creds, options=[
        ('grpc.max_send_message_length', 50 * 1024 * 1024),
        ('grpc.max_receive_message_length', 50 * 1024 * 1024)
        ])

# Creating a stub and requesting the client for the latest network graph and graph info
stub = lnrpc.LightningStub(channel)
graphRequest = ln.ChannelGraphRequest(include_unannounced=True)
networkInfoRequest = ln.NetworkInfoRequest()
infoRequest = ln.request = ln.GetInfoRequest()
graphResponse = stub.DescribeGraph(graphRequest, metadata=[('macaroon', macaroon)])
networkInfoResponse = stub.GetNetworkInfo(networkInfoRequest, metadata=[('macaroon', macaroon)])
infoResponse = stub.GetInfo(infoRequest, metadata=[('macaroon', macaroon)])

# GetNetworkInfo returns some basic stats about the known channel graph from the point of view of the node.
print("Network Info: \n\n" + str(networkInfoResponse))

# GetInfo returns general information concerning the lightning node including
# it's identity pubkey, alias, the chains it is connected to, and information concerning the number of open+pending channels.
print("Info: \n\n" + str(infoResponse))

# Treat the response and build a multi line adjancency list from it
# https://networkx.github.io/documentation/stable/reference/readwrite/multiline_adjlist.html
adjListDic = defaultdict(list)
		#if p==1:

			#pass

		#else:

			#print('There is a variable. It is "',master[i],'"')

 
ans=calculate(master,0)


print("The result of the above equation is",ans,"\n")
the_end = process.memory_info().rss
mem_tot = the_end - beginning
print("End", the_end, "bytes", mem_tot, "bytes", psutil.cpu_freq(), "MHz")

satoshi_amt = round(mem_tot*0.0000845)

print("The cost is", satoshi_amt, "sats")


response = stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)])
print(response.total_balance, "Satoshis")

response_two = stub.GetInfo(ln.GetInfoRequest(), metadata=[('macaroon', macaroon)])
print(response_two)



Beispiel #27
0
 def getinfo(self):
     try:
         response = self.client.GetInfo(ln.GetInfoRequest())
         return response
     except Exception as e:
         logger.exception(e)
Beispiel #28
0
 def get_info(self):
     return self.stub.GetInfo(ln.GetInfoRequest())
Beispiel #29
0
def metadata_callback(context, callback):
    # for more info see grpc docs
    callback([('macaroon', macaroon)], None)

# 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()

# 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)

# now every call will be made with the macaroon already included
stub.GetInfo(ln.GetInfoRequest())