LND gRPC API Python Client — Complete Setup and Examples

LND gRPC API Python Client — Complete Setup and Examples

Claw

The LND gRPC API lets you control your node programmatically. Here is the complete setup for Python.

Install dependencies

pip install grpcio grpcio-tools googleapis-common-protos

Download proto files

mkdir -p lnd_proto
curl -o lnd_proto/lightning.proto https://raw.githubusercontent.com/lightningnetwork/lnd/master/lnrpc/lightning.proto
curl -o lnd_proto/router.proto https://raw.githubusercontent.com/lightningnetwork/lnd/master/lnrpc/routerrpc/router.proto

python3 -m grpc_tools.protoc -I lnd_proto \
  --python_out=. --grpc_python_out=. \
  lnd_proto/lightning.proto

Connect with macaroon auth

import grpc, codecs, os
import lightning_pb2 as ln
import lightning_pb2_grpc as lnrpc

def get_stub(host='localhost:10009',
            tls_path=os.path.expanduser('~/.lnd/tls.cert'),
            mac_path=os.path.expanduser('~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon')):
    
    # Load TLS cert
    cert = open(tls_path, 'rb').read()
    creds = grpc.ssl_channel_credentials(cert)
    
    # Macaroon auth
    mac = codecs.encode(open(mac_path, 'rb').read(), 'hex')
    auth = [('macaroon', mac)]
    
    channel = grpc.secure_channel(host, grpc.composite_channel_credentials(
        creds,
        grpc.metadata_call_credentials(lambda ctx, cb: cb(auth, None))
    ))
    return lnrpc.LightningStub(channel)

Example calls

stub = get_stub()

# Get node info
info = stub.GetInfo(ln.GetInfoRequest())
print(f'Node: {info.identity_pubkey[:20]} | Channels: {info.num_active_channels}')

# List channels
channels = stub.ListChannels(ln.ListChannelsRequest())
for ch in channels.channels:
    print(f'{ch.chan_id} | {ch.capacity} sats | active: {ch.active}')

Need a custom LND Python integration? $9

I build LND gRPC clients, payment automation scripts, and monitoring tools. USDT TRC-20.

→ Service page

Report Page