-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathfeeadjuster.py
executable file
·377 lines (326 loc) · 13.7 KB
/
feeadjuster.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
#!/usr/bin/env python3
import random
import statistics
import time
from pyln.client import Plugin, Millisatoshi, RpcError
from threading import Lock
plugin = Plugin()
# Our amount and the total amount in each of our channel, indexed by scid
plugin.adj_balances = {}
# Cache to avoid loads of RPC calls
plugin.our_node_id = None
plugin.peers = None
plugin.channels = None
# Users can configure this
plugin.update_threshold = 0.05
# forward_event must wait for init
plugin.mutex = Lock()
plugin.mutex.acquire()
def get_adjusted_percentage(plugin: Plugin, scid: str):
"""
For big channels, there may be a wide range where the liquidity is just okay.
Note: if big_enough_liquidity is greater than {total} * 2
then percentage is actually {our} / {total}, as it was before
"""
channel = plugin.adj_balances[scid]
if plugin.big_enough_liquidity == Millisatoshi(0):
return channel["our"] / channel["total"]
min_liquidity = min(channel["total"] / 2, int(plugin.big_enough_liquidity))
theirs = channel["total"] - channel["our"]
if channel["our"] >= min_liquidity and theirs >= min_liquidity:
# the liquidity is just okay
return 0.5
if channel["our"] < min_liquidity:
# our liquidity is too low
return channel["our"] / min_liquidity / 2
# their liquidity is too low
return (min_liquidity - theirs) / min_liquidity / 2 + 0.5
def get_ratio_soft(our_percentage):
"""
Basic algorithm: lesser difference than default
"""
return 10**(0.5 - our_percentage)
def get_ratio(our_percentage):
"""
Basic algorithm: the farther we are from the optimal case, the more we
bump/lower.
"""
return 50**(0.5 - our_percentage)
def get_ratio_hard(our_percentage):
"""
Return value is between 0 and 20: 0 -> 20; 0.5 -> 1; 1 -> 0
"""
return 100**(0.5 - our_percentage) * (1 - our_percentage) * 2
def get_peer_id_for_scid(plugin: Plugin, scid: str):
for peer in plugin.peers:
for ch in peer['channels']:
if ch['short_channel_id'] == scid:
return peer['id']
return None
def get_local_channel_for_scid(plugin: Plugin, scid: str):
for peer in plugin.peers:
for ch in peer['channels']:
if ch['short_channel_id'] == scid:
return ch
return None
def get_chan_fees(plugin: Plugin, scid: str):
channel = get_local_channel_for_scid(plugin, scid)
assert channel is not None
return {"base": channel["fee_base_msat"], "ppm": channel["fee_proportional_millionths"]}
def get_fees_global(plugin: Plugin, scid: str):
return {"base": plugin.adj_basefee, "ppm": plugin.adj_ppmfee}
def get_fees_median(plugin: Plugin, scid: str):
""" Median fees from peers or peer.
The assumption is that our node competes in fees to other peers of a peer.
"""
peer_id = get_peer_id_for_scid(plugin, scid)
assert peer_id is not None
if plugin.listchannels_by_dst:
plugin.channels = plugin.rpc.call("listchannels",
{"destination": peer_id})['channels']
channels_to_peer = [ch for ch in plugin.channels
if ch['destination'] == peer_id
and ch['source'] != plugin.our_node_id]
if len(channels_to_peer) == 0:
return None
fees_ppm = [ch['fee_per_millionth'] for ch in channels_to_peer]
return {"base": plugin.adj_basefee, "ppm": statistics.median(fees_ppm)}
def setchannelfee(plugin: Plugin, scid: str, base: int, ppm: int):
fees = get_chan_fees(plugin, scid)
if fees is None or base == fees['base'] and ppm == fees['ppm']:
return False
try:
plugin.rpc.setchannelfee(scid, base, ppm)
return True
except RpcError as e:
plugin.log(f"Could not adjust fees for channel {scid}: '{e}'", level="error")
return False
def significant_update(plugin: Plugin, scid: str):
channel = plugin.adj_balances[scid]
last_liquidity = channel.get("last_liquidity")
if last_liquidity is None:
return True
# Only update on substantial balance moves to avoid flooding, and add
# some pseudo-randomness to avoid too easy channel balance probing
update_threshold = plugin.update_threshold
update_threshold_abs = int(plugin.update_threshold_abs)
if not plugin.deactivate_fuzz:
update_threshold += random.uniform(-0.015, 0.015)
update_threshold_abs += update_threshold_abs * random.uniform(-0.015, 0.015)
last_percentage = last_liquidity / channel["total"]
percentage = channel["our"] / channel["total"]
if (abs(last_percentage - percentage) > update_threshold
or abs(last_liquidity - channel["our"]) > update_threshold_abs):
return True
return False
def maybe_adjust_fees(plugin: Plugin, scids: list):
channels_adjusted = 0
for scid in scids:
our = plugin.adj_balances[scid]["our"]
total = plugin.adj_balances[scid]["total"]
percentage = our / total
base = plugin.adj_basefee
ppm = plugin.adj_ppmfee
# select ideal values per channel
fees = plugin.fee_strategy(plugin, scid)
if fees is not None:
base = fees['base']
ppm = fees['ppm']
# reset to normal fees if imbalance is not high enough
if (percentage > plugin.imbalance and percentage < 1 - plugin.imbalance):
if setchannelfee(plugin, scid, base, ppm):
plugin.log(f"Set default fees as imbalance is too low: {scid}")
plugin.adj_balances[scid]["last_liquidity"] = our
channels_adjusted += 1
continue
if not significant_update(plugin, scid):
continue
percentage = get_adjusted_percentage(plugin, scid)
assert 0 <= percentage and percentage <= 1
ratio = plugin.get_ratio(percentage)
if setchannelfee(plugin, scid, int(base), int(ppm * ratio)):
plugin.log(f"Adjusted fees of {scid} with a ratio of {ratio}")
plugin.adj_balances[scid]["last_liquidity"] = our
channels_adjusted += 1
return channels_adjusted
def get_chan(plugin: Plugin, scid: str):
for peer in plugin.peers:
for chan in peer["channels"]:
if chan.get("short_channel_id") == scid:
return chan
def maybe_add_new_balances(plugin: Plugin, scids: list):
for scid in scids:
if scid not in plugin.adj_balances:
chan = get_chan(plugin, scid)
assert chan is not None
plugin.adj_balances[scid] = {
"our": int(chan["to_us_msat"]),
"total": int(chan["total_msat"])
}
@plugin.subscribe("forward_event")
def forward_event(plugin: Plugin, forward_event: dict, **kwargs):
if not plugin.forward_event_subscription:
return
plugin.mutex.acquire(blocking=True)
plugin.peers = plugin.rpc.listpeers()["peers"]
if plugin.fee_strategy == get_fees_median and not plugin.listchannels_by_dst:
plugin.channels = plugin.rpc.listchannels()['channels']
if forward_event["status"] == "settled":
in_scid = forward_event["in_channel"]
out_scid = forward_event["out_channel"]
maybe_add_new_balances(plugin, [in_scid, out_scid])
plugin.adj_balances[in_scid]["our"] += forward_event["in_msatoshi"]
plugin.adj_balances[out_scid]["our"] -= forward_event["out_msatoshi"]
try:
# Pseudo-randomly add some hysterisis to the update
if not plugin.deactivate_fuzz and random.randint(0, 9) == 9:
time.sleep(random.randint(0, 5))
maybe_adjust_fees(plugin, [in_scid, out_scid])
except Exception as e:
plugin.log("Adjusting fees: " + str(e), level="error")
plugin.mutex.release()
@plugin.method("feeadjust")
def feeadjust(plugin: Plugin, scid: str = None):
"""Adjust fees for all channels (default) or just a given `scid`.
This method is automatically called in plugin init, or can be called manually after a successful payment.
Otherwise, the plugin keeps the fees up-to-date.
"""
plugin.mutex.acquire(blocking=True)
plugin.peers = plugin.rpc.listpeers()["peers"]
if plugin.fee_strategy == get_fees_median and not plugin.listchannels_by_dst:
plugin.channels = plugin.rpc.listchannels()['channels']
channels_adjusted = 0
for peer in plugin.peers:
for chan in peer["channels"]:
if chan["state"] == "CHANNELD_NORMAL":
_scid = chan["short_channel_id"]
if scid != None and scid != _scid:
continue
plugin.adj_balances[_scid] = {
"our": int(chan["to_us_msat"]),
"total": int(chan["total_msat"])
}
channels_adjusted += maybe_adjust_fees(plugin, [_scid])
msg = f"{channels_adjusted} channel(s) adjusted"
plugin.log(msg)
plugin.mutex.release()
return msg
@plugin.method("feeadjuster-toggle")
def feeadjuster_toggle(plugin: Plugin, value: bool = None):
"""Activates/Deactivates automatic fee updates for forward events.
The status will be set to value.
"""
msg = {"forward_event_subscription": {"previous": plugin.forward_event_subscription}}
if value is None:
plugin.forward_event_subscription = not plugin.forward_event_subscription
else:
plugin.forward_event_subscription = bool(value)
msg["forward_event_subscription"]["current"] = plugin.forward_event_subscription
return msg
@plugin.init()
def init(options: dict, configuration: dict, plugin: Plugin, **kwargs):
plugin.our_node_id = plugin.rpc.getinfo()["id"]
plugin.deactivate_fuzz = options.get("feeadjuster-deactivate-fuzz")
plugin.forward_event_subscription = not options.get("feeadjuster-deactivate-fee-update")
plugin.update_threshold = float(options.get("feeadjuster-threshold"))
plugin.update_threshold_abs = Millisatoshi(options.get("feeadjuster-threshold-abs"))
plugin.big_enough_liquidity = Millisatoshi(options.get("feeadjuster-enough-liquidity"))
plugin.imbalance = float(options.get("feeadjuster-imbalance"))
adjustment_switch = {
"soft": get_ratio_soft,
"hard": get_ratio_hard,
"default": get_ratio
}
plugin.get_ratio = adjustment_switch.get(options.get("feeadjuster-adjustment-method"), get_ratio)
fee_strategy_switch = {
"global": get_fees_global,
"median": get_fees_median
}
plugin.fee_strategy = fee_strategy_switch.get(options.get("feeadjuster-feestrategy"), get_fees_global)
config = plugin.rpc.listconfigs()
plugin.adj_basefee = config["fee-base"]
plugin.adj_ppmfee = config["fee-per-satoshi"]
# normalize the imbalance percentage value to 0%-50%
if plugin.imbalance < 0 or plugin.imbalance > 1:
raise ValueError("feeadjuster-imbalance must be between 0 and 1.")
if plugin.imbalance > 0.5:
plugin.imbalance = 1 - plugin.imbalance
# detect if server supports the new listchannels by `destination` (#4614)
plugin.listchannels_by_dst = False
rpchelp = plugin.rpc.help().get('help')
if len([c for c in rpchelp if c["command"].startswith("listchannels ")
and "destination" in c["command"]]) == 1:
plugin.listchannels_by_dst = True
plugin.log(f"Plugin feeadjuster initialized "
f"({plugin.adj_basefee} base / {plugin.adj_ppmfee} ppm) with an "
f"imbalance of {int(100 * plugin.imbalance)}%/{int(100 * ( 1 - plugin.imbalance))}%, "
f"update_threshold: {int(100 * plugin.update_threshold)}%, "
f"update_threshold_abs: {plugin.update_threshold_abs}, "
f"enough_liquidity: {plugin.big_enough_liquidity}, "
f"deactivate_fuzz: {plugin.deactivate_fuzz}, "
f"forward_event_subscription: {plugin.forward_event_subscription}, "
f"adjustment_method: {plugin.get_ratio.__name__}, "
f"fee_strategy: {plugin.fee_strategy.__name__}, "
f"listchannels_by_dst: {plugin.listchannels_by_dst}")
plugin.mutex.release()
feeadjust(plugin)
plugin.add_option(
"feeadjuster-deactivate-fuzz",
False,
"Deactivate update threshold randomization and hysterisis.",
"flag"
)
plugin.add_option(
"feeadjuster-deactivate-fee-update",
False,
"Deactivate automatic fee updates for forward events.",
"flag"
)
plugin.add_option(
"feeadjuster-threshold",
"0.05",
"Relative channel balance delta at which to trigger an update. Default 0.05 means 5%. "
"Note: it's also fuzzed by 1.5%",
"string"
)
plugin.add_option(
"feeadjuster-threshold-abs",
"0.001btc",
"Absolute channel balance delta at which to always trigger an update. "
"Note: it's also fuzzed by 1.5%",
"string"
)
plugin.add_option(
"feeadjuster-enough-liquidity",
"0msat",
"Beyond this liquidity do not adjust fees. "
"This also modifies the fee curve to achieve having this amount of liquidity. "
"Default: '0msat' (turned off).",
"string"
)
plugin.add_option(
"feeadjuster-adjustment-method",
"default",
"Adjustment method to calculate channel fee"
"Can be 'default', 'soft' for less difference or 'hard' for higher difference"
"string"
)
plugin.add_option(
"feeadjuster-imbalance",
"0.5",
"Ratio at which channel imbalance the feeadjuster should start acting. "
"Default: 0.5 (always). Set higher or lower values to limit feeadjuster's "
"activity to more imbalanced channels. "
"E.g. 0.3 for '70/30'% or 0.6 for '40/60'%.",
"string"
)
plugin.add_option(
"feeadjuster-feestrategy",
"global",
"Sets the per channel fee selection strategy. "
"Can be 'global' to use global config or default values, "
"or 'median' to use the median fees from peers of peer "
"Default: 'global'.",
"string"
)
plugin.run()