Exemplo n.º 1
0
def listactivechannels():
	ac = []
	chans = stub.ListChannels(ln.ListChannelsRequest()).channels
	for chan in chans:
		if chan.active:
			ac.append(chan)
	return ac
Exemplo n.º 2
0
 def get_channels(self):
     if self.channels is None:
         request = ln.ListChannelsRequest(
             active_only=True,
         )
         self.channels = self.stub.ListChannels(request).channels
     return self.channels
def getActiveChannelList():
    channel_request = ln.ListChannelsRequest(
        active_only=True,
        inactive_only=False,
        public_only=False,
        private_only=False,
    )
    return stub.ListChannels(channel_request)
Exemplo n.º 4
0
async def r_liquidity(*_):
    req = ln.ListChannelsRequest(public_only=True)
    channels = (await LND.stub.ListChannels(req)).channels
    return {
        "inbound":
        sum(x.remote_balance - x.remote_chan_reserve_sat for x in channels),
        "outbound":
        sum(x.local_balance - x.local_chan_reserve_sat for x in channels),
    }
Exemplo n.º 5
0
def scan_channel(my_channel_id: int, scan_channel_id: int):
    # Grab some initial data and make sure everything came back OK
    node = init_node()
    my_channels = node.ListChannels(ln.ListChannelsRequest()).channels
    my_channel = [c for c in my_channels if c.chan_id == my_channel_id][0]
    channel = node.GetChanInfo(ln.ChanInfoRequest(chan_id=scan_channel_id))

    if not my_channel:
        raise Exception(f'You have no channel with ID "{my_channel_id}"')
    if not channel:
        raise Exception(f'Unknown channel with ID "{scan_channel_id}"')

    # Determine the max we can scan, and who's the "receiver"
    maximum = min(
        int(channel.capacity),
        int(my_channel.local_balance),
        MAX_PAYMENT_SIZE,
    )
    dest_pubkey = channel.node2_pub if my_channel.remote_pubkey == channel.node1_pub else channel.node2_pub

    # Loop send bogus payments until we find the balance
    low = 0
    high = maximum

    print(f'Beginning scan of channel {scan_channel_id}, max scannable {maximum} satoshis...')
    while high - low > 1:
        test_amount = math.ceil((low + high) / 2)
        print(f'Probing with a {test_amount} sat payment...')

        res = node.SendPaymentSync(ln.SendRequest(
            dest_string=dest_pubkey,
            amt=test_amount,
            payment_hash_string=make_random_hash(),
            outgoing_chan_id=my_channel.chan_id,
            final_cltv_delta=144,
        ))
        err = res.payment_error

        # Depending on the error, raise or lower the amount. The route note having
        # enough capacity comes in many shapes and sizes of error, so we have to
        # check for a few types here.
        if 'UnknownPaymentHash' in err:
            print('Amount was too low, raising lower bound...')
            low = test_amount
        elif 'unable to find a path' in err or \
                'insufficient' in err or \
                'TemporaryChannelFailure' in err:
            print('Amount was too high, lowering upper bound...')
            high = test_amount
        else:
            raise Exception(f'Unknown error occured when trying to scan: {err}')

    print(f'Balance for channel ${scan_channel_id} is between {low} and {high} satoshis!')
    if high == maximum:
        print(f'NOTE: The balance exceeds the height we were able to scan, so it may be larger than {maximum} satoshis')
Exemplo n.º 6
0
    def _channel_with_remote(self, remote):
        self_id = self.id()
        remote_id = remote.id()
        channels = self.daemon.stub.ListChannels(
            lnrpc.ListChannelsRequest()).channels
        channel_by_remote = {c.remote_pubkey: c for c in channels}
        if remote_id not in channel_by_remote:
            self.logger.warning("Channel {} -> {} not found".format(
                self_id, remote_id))
            return False

        return channel_by_remote[remote_id]
Exemplo n.º 7
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
Exemplo n.º 8
0
    def check_channel(self, remote):
        """ Make sure that we have an active channel with remote
        """
        self_id = self.id()
        remote_id = remote.id()
        channels = self.rpc.stub.ListChannels(lnrpc.ListChannelsRequest()).channels
        channel_by_remote = {c.remote_pubkey: c for c in channels}
        if remote_id not in channel_by_remote:
            self.logger.warning("Channel {} -> {} not found".format(self_id, remote_id))
            return False

        channel = channel_by_remote[remote_id]
        self.logger.debug("Channel {} -> {} state: {}".format(self_id, remote_id, channel))
        return channel.active
Exemplo n.º 9
0
async def open_channels(self,
                        *_,
                        active: bool = False,
                        inactive: bool = False,
                        public: bool = False,
                        private: bool = False,
                        peer: Optional[bytes] = None):
    req = ln.ListChannelsRequest(
        active_only=active,
        inactive_only=inactive,
        public_only=public,
        private_only=private,
    )
    r = await LND.stub.ListChannels(req)
    return r.channels
Exemplo n.º 10
0
def main():
    request = ln.ListChannelsRequest(
        active_only=False,
        inactive_only=False,
        public_only=False,
        private_only=False,
    )
    response = stub.ListChannels(request)

    if True:
        print('%35s' % 'chan_alias', '%18s' % 'chan_id',
              '%66s' % 'chan.remote_pubkey', '%5s' % 'active', '%3s' % 'htlcs',
              '%3s' % 'pri', '%9s' % 'remotebal', '%9s' % 'bal+myfee',
              '%7s' % 'myfee', '%10s' % 'usagerat', '%9s' % 'locbal',
              '%9s' % 'chancap', '%9s' % 'cap %')

    response.channels.sort(key=operator.attrgetter('initiator'), reverse=True)

    is_pending_htlcs = False

    for chan in response.channels:
        printOneChannel(chan, 'active')
        if (len(chan.pending_htlcs) > 0):
            is_pending_htlcs = True

    request_pending = ln.PendingChannelsRequest()
    response_pending = stub.PendingChannels(request_pending)
    #print(response_pending)

    for chan in response_pending.pending_open_channels:
        #print(chan)
        printOneChannel(chan, 'pending')

    print('total_limbo_balance=', response_pending.total_limbo_balance)

    msg = ''
    if (is_pending_htlcs):
        msg = 'note: balance may not reflect accurately if there are pending stuck HTLCs'

    tot_local_pct = round(100 * all_channel_val / all_channel_cap, 1)
    print('TOTAL (sat): ', all_channel_val, '/', all_channel_cap, '=',
          str(tot_local_pct), '%')
    print('TOTAL (BTC): ', all_channel_val / 100000000, 'BTC', '/',
          all_channel_cap / 100000000, 'BTC ' + msg)
Exemplo n.º 11
0
 def list_channels(self):
     try:
         response = self.client.ListChannels(ln.ListChannelsRequest())
         return response
     except Exception as e:
         logger.exception(e)
Exemplo n.º 12
0
def getCurrentChannels(stub, macaroon):
    responseChannels = stub.ListChannels(ln.ListChannelsRequest(),
                                         metadata=[('macaroon', macaroon)])
    return responseChannels.channels
Exemplo n.º 13
0
def peerpage():
    try:
        rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,allowed_ip,rpc_port))
        chain_type = rpc_connect.getblockchaininfo()['chain']
        if chain_type == "test":
            chaintype_ln = "testnet"
        else:
            chaintype_ln = "mainnet"
        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)

        pbks = stub.ListChannels(ln.ListChannelsRequest(), metadata=[('macaroon', macaroon)])
        pubkey_list = [str(i.remote_pubkey) for i in pbks.channels]

        response = stub.ListPeers(ln.ListPeersRequest(), metadata=[('macaroon', macaroon)])
        show_current_peers = response.peers
        show_current_peers_list = []
        for peer in show_current_peers:
            if peer.pub_key in pubkey_list:
              show_current_peers_list.append((str(peer.pub_key), True))
            else:
              show_current_peers_list.append((str(peer.pub_key), False))
        conn = True
        length_of = len(show_current_peers_list)

    except:
        show_current_peers_list = ["Offline!"]
        length_of = 0
        conn = False
        pubkey_list = ["Offline!"]

    if conn == True:
      if request.method == 'POST':
        if request.form['action'] == "connectbutton":
          if len(request.form['text']) > 10:
            response_uri = str(request.form['text'])
            result = response_uri.strip()

            def connect(host, port, node_id):
               addr = ln.LightningAddress(pubkey=node_id, host="{}:{}".format(host, port))
               req = ln.ConnectPeerRequest(addr=addr, perm=True)
               stub.ConnectPeer(ln.ConnectPeerRequest(addr=addr,perm=False), metadata=[('macaroon',macaroon)])
            try:
               nodeid, lnhost, lnport = result[:66], result[67:-5], result[-4:]
               connect(lnhost,lnport,nodeid)
               show_current_peers_list.append((nodeid, False))
               length_of = len(show_current_peers_list)
               result = "Successfully connected!"
               return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="SuccessCon", conn=conn)
            except:
               return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="FalseCon", conn=conn)
          else:
            return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="FalseCon", conn=conn)
        else:
          if len(request.form['text']) > 10:
            response_uri = str(request.form['text'])
            result = response_uri.strip()
            def disconnect(pubkey):
                req = ln.DisconnectPeerRequest(pub_key=pubkey)
                stub.DisconnectPeer(ln.DisconnectPeerRequest(pub_key=pubkey), metadata=[('macaroon',macaroon)])
            try:
                disconnect(result)
                del show_current_peers_list[-1]
                length_of = len(show_current_peers_list)
                return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="SuccessDis", conn=conn)
            except:
                return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="FalseDis", conn=conn)
          else:
            return render_template('peerpage.html', len=len(show_current_peers_list), show_current_peers=show_current_peers_list, length_of=length_of, result="FalseDis", conn=conn)
    return render_template('peerpage.html', len=len(show_current_peers_list), length_of=length_of, show_current_peers=show_current_peers_list, conn=conn)               
Exemplo n.º 14
0
import rpc_pb2 as ln, rpc_pb2_grpc as lnrpc
import code
import codecs, grpc, os
import json

# mac_path = '/root/.lnd/data/chain/bitcoin/mainnet/admin.macaroon'
mac_path = '/root/.lnd/data/chain/litecoin/mainnet/admin.macaroon'

macaroon = codecs.encode(open(mac_path, 'rb').read(), 'hex')
os.environ['GRPC_SSL_CIPHER_SUITES'] = 'HIGH+ECDSA'
cert = open('/root/.lnd/tls.cert', 'rb').read()
ssl_creds = grpc.ssl_channel_credentials(cert)
channel = grpc.secure_channel('localhost:10009', ssl_creds)
stub = lnrpc.LightningStub(channel)

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

for chan in response.channels:
    request = ln.NodeInfoRequest(pub_key=chan.remote_pubkey)
    r = stub.GetNodeInfo(request, metadata=[('macaroon', macaroon)])
    chan_partner_alias = r.node.alias
    print("%s\t%s\t%f" % (chan_partner_alias, chan.remote_pubkey,
                          (chan.local_balance /
                           (chan.local_balance + chan.remote_balance))))

request = ln.InvoiceSubscription(
    add_index=0,
    settle_index=0,
)
# Query routes for one direction
Exemplo n.º 15
0
def channelpage():
    try:
        rpc_connect = AuthServiceProxy("http://{}:{}@{}:{}".format(rpc_user,rpc_password,allowed_ip,rpc_port))
        chain_type = rpc_connect.getblockchaininfo()['chain']
        if chain_type == "test":
            chaintype_ln = "testnet"
        else:
            chaintype_ln = "mainnet"
        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.ListChannels(ln.ListChannelsRequest(), metadata=[('macaroon', macaroon)])
        walbal = stub.WalletBalance(ln.WalletBalanceRequest(), metadata=[('macaroon', macaroon)])
        availablefunds = walbal.confirmed_balance
        channellist = response.channels
        closedchannelidentifiers = []
        channelidentifiers = []
        pendingchannelidentifiers = []

        pendingresponse = stub.PendingChannels(ln.PendingChannelsRequest(), metadata=[('macaroon', macaroon)])
        pend = pendingresponse.pending_open_channels
        for i in pend:
          k = ((str(i.channel.remote_node_pub)), str(i.channel.channel_point), int(i.channel.capacity), int(i.channel.local_balance))
          pendingchannelidentifiers.append(k)
        length_of_pending = len(pendingchannelidentifiers)

        closedresponse = stub.ClosedChannels(ln.ClosedChannelsRequest(), metadata=[('macaroon', macaroon)])
        for i in closedresponse.channels:
         p = (str(i.remote_pubkey), str(i.channel_point), int(i.capacity), int(i.close_height), int(i.settled_balance))
         closedchannelidentifiers.append(p)
        length_of_closed = len(closedchannelidentifiers)

        for i in channellist:
         if i.active == True:
          k = (str(i.remote_pubkey), int(i.capacity), int(i.local_balance), int(i.remote_balance), int(i.commit_fee), str(i.channel_point))
          channelidentifiers.append(k)
        conn = True
        length_of = len(channelidentifiers)
        try:
         outcap = sum(zip(*channelidentifiers)[2])
         incap = sum(zip(*channelidentifiers)[3])
        except:
         outcap = incap = 0
         length_of = 0


    except:
        conn = False

    if conn == True:
      if request.method == "POST":
        if request.form['action'] == "openchan":
              try:
                pkstring = str(request.form['channelpubkey'])
                locfundamt = int(request.form['channelamt'])
                response = stub.OpenChannelSync(ln.OpenChannelRequest(node_pubkey_string=pkstring, local_funding_amount=locfundamt, push_sat=0), metadata=[('macaroon', macaroon)])
                if response.funding_txid_bytes:
                  return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                   outcap=outcap, incap=incap, conn=conn, opened="True", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)   
              except:
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                   outcap=outcap, incap=incap, conn=conn, opened="True", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
        elif request.form['action'] == "closechan":
              try:
                return ln.ChannelPoint(funding_txid_string=str(request.form['channelpubkey']))
                stub.CloseChannel(ln.CloseChannelRequest(channel_point=channelpoint), metadata=[('macaroon', macaroon)])
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                 outcap=outcap, incap=incap, conn=conn, closed="pendclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
              except:
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                 outcap=outcap, incap=incap, conn=conn, closed="couldntclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
        elif request.form['action'] == "fclosechan":
              try:
                return ln.ChannelPoint(funding_txid_string=str(request.form['channelpubkey']))
                stub.CloseChannel(ln.CloseChannelRequest(channel_point=channelpoint, force=True), metadata=[('macaroon', macaroon)])
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                 outcap=outcap, incap=incap, conn=conn, closed="pendclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
              except:
                return render_template('channels.html', availablefunds=availablefunds, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers,
                 outcap=outcap, incap=incap, conn=conn, closed="couldntclose", length_of=length_of, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)
      else:
        return render_template('channels.html', conn=conn, length_of=length_of, channelidentifiers=channelidentifiers, closedchannelidentifiers=closedchannelidentifiers, incap=incap,
     outcap=outcap, availablefunds=availablefunds, length_of_closed=length_of_closed, pendingchannelidentifiers=pendingchannelidentifiers, length_of_pending=length_of_pending)

    return render_template('channels.html', conn=conn, length_of=0, channelidentifiers=0, closedchannelidentifiers=0, incap=0,
     outcap=0, availablefunds=0, length_of_closed=0, pendingchannelidentifiers=0, length_of_pending=0)
Exemplo n.º 16
0
def metadata_callback(context, callback):
    mac_file = "~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon"
    with open(os.path.expanduser(mac_file), "rb") as f:
        macaroon_bytes = f.read()
        macaroon = codecs.encode(macaroon_bytes, "hex")
        callback([("macaroon", macaroon)], None)


cert = open(os.path.expanduser("~/.lnd/tls.cert"), "rb").read()
cert_creds = grpc.ssl_channel_credentials(cert)
auth_creds = grpc.metadata_call_credentials(metadata_callback)
combined_creds = grpc.composite_channel_credentials(cert_creds, auth_creds)
channel = grpc.secure_channel("localhost:10009", combined_creds)
stub = lnrpc.LightningStub(channel)

channel_info = stub.ListChannels(ln.ListChannelsRequest()).channels

fields = [
    "remote_pubkey",
    "chan_id",
    "active",
    "capacity",
    "local_balance",
    "remote_balance",
    "csv_delay",
    "private",
]
chan_data = [[getattr(c, f) for f in fields] for c in channel_info]
df_chan = pd.DataFrame(chan_data, columns=fields).set_index("chan_id")
print(df_chan.sort_values(["active", "capacity", "private"], ascending=False))
print("\ncapital: {}".format(df_chan.local_balance.sum()))
Exemplo n.º 17
0
def get_channels(active_only=True):

    # channels
    if active_only:
        request = ln.ListChannelsRequest(active_only=True)
    else:
        request = ln.ListChannelsRequest(inactive_only=True)

    response = stub.ListChannels(request, metadata=[('macaroon', macaroon)])
    channels_ = response.channels

    channels = sorted(channels_, key=lambda c: int(c.chan_id), reverse=False)

    channel_number = 0
    channels_with_names = {}

    request = ln.ForwardingHistoryRequest(
        start_time=int(time.time() - 24 * 60 * 60),
        end_time=int(time.time() + 24 * 60 * 60),
        #index_offset=<uint32>,
        #num_max_events=<uint32>,
    )
    response = stub.ForwardingHistory(request,
                                      metadata=[('macaroon', macaroon)])

    channel_events = {}

    for event in response.forwarding_events:
        if str(event.chan_id_in) in channel_events:
            channel_events[str(event.chan_id_in)]["in"] += 1
            channel_events[str(event.chan_id_in)]["amt_in"] += event.amt_in
            #channel_events[str(event.chan_id_in)]["amt_out"] += event.amt_out
            channel_events[str(event.chan_id_in)]["fee"] += event.fee
        else:
            channel_events[str(event.chan_id_in)] = {
                "in": 1,
                "out": 0,
                "amt_in": event.amt_in,
                "amt_out": 0,  #event.amt_out,
                "fee": event.fee
            }
        if str(event.chan_id_out) in channel_events:
            channel_events[str(event.chan_id_out)]["out"] += 1
            #channel_events[str(event.chan_id_out)]["amt_in"] += event.amt_in
            channel_events[str(event.chan_id_out)]["amt_out"] += event.amt_out
            channel_events[str(event.chan_id_out)]["fee"] += event.fee
        else:
            channel_events[str(event.chan_id_out)] = {
                "in": 0,
                "out": 1,
                "amt_in": 0,  #event.amt_in,
                "amt_out": event.amt_out,
                "fee": event.fee
            }

    #print "%d active channels" % (len(channels))
    max_capacity = max([c.capacity for c in channels])
    for channel in channels:
        channels_with_names[str(channel_number).rjust(2)] = {
            "channel": channel
        }
        capacity = channel.capacity
        local_balance = channel.local_balance
        chan_id = str(channel.chan_id)
        remote_pubkey = channel.remote_pubkey
        node_alias = get_node_alias(channel_graph,
                                    remote_pubkey).encode("utf8").decode(
                                        "ascii", "ignore")

        if len(node_alias) >= 15:
            node_alias = node_alias[:13] + "/"
        else:
            node_alias += " " * (15 - 1 - len(node_alias))
        pass

        score = channel_score(capacity, local_balance)
        channels_with_names[str(channel_number).rjust(2)]["score"] = score
        if chan_id in channel_events.keys():
            channel_transactions = "    24h: <- %d, -> %d" % (
                channel_events[chan_id]["in"], channel_events[chan_id]["out"])
            channel_transactions += " %d in, %d out, %d fees" % (
                channel_events[chan_id]["amt_in"],
                channel_events[chan_id]["amt_out"],
                channel_events[chan_id]["fee"])
        else:
            channel_transactions = " "

        yield (str(channel_number).rjust(2) + "/ " + chan_id + " " +
               node_alias + " " +
               channel_cursor(capacity, local_balance, max_capacity, score)
               #+ " " + remote_pubkey
               + channel_transactions)
        channel_number += 1
Exemplo n.º 18
0
def get_channels():
    request = ln.ListChannelsRequest(public_only=True)
    return stub.ListChannels(request,
                             metadata=[('macaroon', macaroon)]).channels
Exemplo n.º 19
0
def listchannels():
	return stub.ListChannels(ln.ListChannelsRequest()).channels
Exemplo n.º 20
0
 def get_channels(self):
     request = ln.ListChannelsRequest(
         active_only=True,
     )
     return self.stub.ListChannels(request).channels
Exemplo n.º 21
0
def main():

    #get currently connected channels (additional information)
    request_channels = ln.ListChannelsRequest(
        active_only=False,
        inactive_only=False,
        public_only=False,
        private_only=False,
    )
    response_channels = stub.ListChannels(request_channels)

    request_graph = ln.ChannelGraphRequest(include_unannounced=False)

    response_graph = stub.DescribeGraph(request_graph)
    #print(response)

    dict_pubkey_chancount = {}
    current_node_pub_key = getCurrentNodePubKey()

    for edge in response_graph.edges:
        #print(edge)

        #check that capacity is above X
        if edge.capacity is not None and edge.capacity >= minCapacitySat:

            if areChannelFeesLow(edge.node1_policy):
                if (edge.node1_pub not in dict_pubkey_chancount):
                    dict_pubkey_chancount[edge.node1_pub] = 1
                else:
                    current_count = dict_pubkey_chancount.get(edge.node1_pub)
                    dict_pubkey_chancount[edge.node1_pub] = current_count + 1
                #print(edge.node1_pub)

            if areChannelFeesLow(edge.node2_policy):
                if (edge.node2_pub not in dict_pubkey_chancount):
                    dict_pubkey_chancount[edge.node2_pub] = 1
                else:
                    current_count = dict_pubkey_chancount.get(edge.node2_pub)
                    dict_pubkey_chancount[edge.node2_pub] = current_count + 1
                #print(edge.node2_pub)

    routesQueried = 0

    #print sorted by channel count (value)
    for chanCount in sorted(set(dict_pubkey_chancount.values()), reverse=True):
        if chanCount >= minChanCount:

            for pubkey, count in dict_pubkey_chancount.items():
                if (count == chanCount):

                    #get info about remote node
                    request_nodeinfo = ln.NodeInfoRequest(pub_key=pubkey, )
                    response_nodeinfo = stub.GetNodeInfo(request_nodeinfo)
                    node_alias = response_nodeinfo.node.alias

                    #check to see if we're connected
                    connected = False
                    for connectedChannel in response_channels.channels:
                        if (pubkey == connectedChannel.remote_pubkey):
                            connected = True

                    if (connected):
                        connectedText = '(connected)'
                    elif (current_node_pub_key == pubkey):
                        connectedText = '(self)'
                    else:
                        connectedText = ''

                    route_fee = 'n/a'
                    first_hop = 'n/a'
                    hop_count = 0
                    if (count >= minChanCountToCalcRoutes):
                        if (count <= maxChanCountToCalcRoutes):
                            #query route to node (might be computationally expensive)
                            request_route = ln.QueryRoutesRequest(
                                pub_key=pubkey,
                                amt=queryAmountSat,
                            )

                            if (routesQueried < maxRoutesToQuery):
                                routesQueried += 1
                                try:
                                    response_route = stub.QueryRoutes(
                                        request_route)

                                    route_fee = str(response_route.routes[0].
                                                    total_fees) + 'sat'

                                    first_hop = response_route.routes[0].hops[
                                        0].chan_id

                                    hop_count = len(
                                        response_route.routes[0].hops)

                                    time.sleep(pauseBetweenRouteQueriesSeconds)

                                except (KeyboardInterrupt, SystemExit):
                                    raise
                                except Exception as e:
                                    if (hasattr(e, 'details')):
                                        if ('unable to find a path to destination'
                                                in str(e.details)):
                                            route_fee = 'NO PATH!'
                                        else:
                                            route_fee = 'ERROR with details'
                                            print(e.details)
                                            print(str(e))
                                    else:
                                        route_fee = 'UNKNOWN ERROR'
                                        print(str(e))

                                #print(dir(response_route))

                            else:
                                route_fee = '(queries >)'
                        else:
                            route_fee = '(skip >)'
                    else:
                        route_fee = '(skip <)'

                    print(pubkey, ":", '%5s' % count, '%8s' % route_fee,
                          '%11s' % connectedText,
                          '%35s' % node_alias.encode('ascii', 'ignore'),
                          '%12s' % first_hop, '%2s' % hop_count)