Skip to content

Instantly share code, notes, and snippets.

@jaonoctus
Created October 22, 2021 01:12
Show Gist options
  • Save jaonoctus/1316bfe9e45dbbf0c25b0f2febd3aa30 to your computer and use it in GitHub Desktop.
Save jaonoctus/1316bfe9e45dbbf0c25b0f2febd3aa30 to your computer and use it in GitHub Desktop.
import json
import subprocess
import sys
def lncli(command):
try:
complete_command = ['lncli'] + command
result_process = subprocess.run(complete_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
except FileNotFoundError:
complete_command = ['docker', 'exec', 'lnd', 'lncli'] + command
result_process = subprocess.run(complete_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
json_result = json.loads(result_process.stdout)
return json_result
def rebalance(amount, fee_limit):
print('Amount:%d Fee Limit:%s' % (amount, fee_limit))
channels = lncli(['listchannels', '--active_only'])['channels']
for channel in channels:
channel['adjust'] = (int(channel['local_balance']) - int(channel['remote_balance'])) / 2
invoice = lncli(['addinvoice', str(amount), '--memo', 'circular rebalance'])['payment_request']
print('Invoice:', invoice)
success = False
for i, a in enumerate(channels):
for b in channels[i + 1:]:
if a['adjust'] <= 0 or b['adjust'] >= 0 or a['adjust'] - b['adjust'] < amount:
continue
print(a['remote_pubkey'], '->', b['remote_pubkey'], end=' | ')
ticket = lncli(['sendpayment', '--force', '--allow_self_payment', '--json',
'--pay_req=' + invoice,
'--outgoing_chan_id', a['chan_id'], '--last_hop', b['remote_pubkey'],
'--fee_limit', str(fee_limit)])
if ticket['status'] == 'SUCCEEDED':
print('OK!')
success = True
break
print(ticket['failure_reason'][15:])
if success:
break
if not success:
lncli(['cancelinvoice', '--paymenthash', invoice])
if __name__ == '__main__':
rebalance(int(sys.argv[1]), int(sys.argv[2]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment