2020-06-26 16:39:02 +02:00
|
|
|
from .lightning import LightningRpc, Millisatoshi
|
2020-01-29 17:02:47 +01:00
|
|
|
from binascii import hexlify
|
2019-01-05 16:55:03 +01:00
|
|
|
from collections import OrderedDict
|
2018-12-18 17:32:16 +01:00
|
|
|
from enum import Enum
|
2019-01-22 19:25:00 +01:00
|
|
|
from threading import RLock
|
2020-06-26 16:39:02 +02:00
|
|
|
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
2019-01-05 16:55:03 +01:00
|
|
|
|
2018-12-10 15:38:21 +01:00
|
|
|
import inspect
|
2020-06-26 16:39:02 +02:00
|
|
|
import io
|
2019-01-03 20:23:02 +01:00
|
|
|
import json
|
2020-09-29 11:26:25 +02:00
|
|
|
import logging
|
2020-01-29 17:02:47 +01:00
|
|
|
import math
|
2019-01-03 20:23:02 +01:00
|
|
|
import os
|
2018-12-29 12:28:52 +01:00
|
|
|
import re
|
2019-01-03 20:23:02 +01:00
|
|
|
import sys
|
2018-12-10 15:38:21 +01:00
|
|
|
import traceback
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
# Notice that this definition is incomplete as it only checks the
|
|
|
|
# top-level. Arrays and Dicts could contain types that aren't encodeable. This
|
|
|
|
# limitation stems from the fact that recursive types are not really supported
|
|
|
|
# yet.
|
|
|
|
JSONType = Union[str, int, float, bool, None, Dict[str, Any], List[Any]]
|
|
|
|
|
|
|
|
# Yes, decorators are weird...
|
|
|
|
NoneDecoratorType = Callable[..., Callable[..., None]]
|
|
|
|
JsonDecoratorType = Callable[..., Callable[..., JSONType]]
|
|
|
|
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2018-12-18 17:32:16 +01:00
|
|
|
class MethodType(Enum):
|
|
|
|
RPCMETHOD = 0
|
|
|
|
HOOK = 1
|
|
|
|
|
|
|
|
|
2019-01-22 19:25:00 +01:00
|
|
|
class RequestState(Enum):
|
|
|
|
PENDING = 'pending'
|
|
|
|
FINISHED = 'finished'
|
|
|
|
FAILED = 'failed'
|
|
|
|
|
|
|
|
|
2019-01-22 17:45:50 +01:00
|
|
|
class Method(object):
|
|
|
|
"""Description of methods that are registered with the plugin.
|
|
|
|
|
|
|
|
These can be one of the following:
|
|
|
|
|
|
|
|
- RPC exposed by RPC passthrough
|
|
|
|
- HOOK registered to be called synchronously by lightningd
|
|
|
|
"""
|
2020-06-26 16:39:02 +02:00
|
|
|
def __init__(self, name: str, func: Callable[..., JSONType],
|
|
|
|
mtype: MethodType = MethodType.RPCMETHOD,
|
|
|
|
category: str = None, desc: str = None,
|
|
|
|
long_desc: str = None, deprecated: bool = False):
|
2019-01-22 17:45:50 +01:00
|
|
|
self.name = name
|
|
|
|
self.func = func
|
|
|
|
self.mtype = mtype
|
2019-05-27 12:58:14 +02:00
|
|
|
self.category = category
|
2019-01-22 19:25:00 +01:00
|
|
|
self.background = False
|
2019-06-30 18:30:05 +02:00
|
|
|
self.desc = desc
|
|
|
|
self.long_desc = long_desc
|
2020-08-06 02:30:56 +02:00
|
|
|
self.deprecated = deprecated
|
2020-10-30 02:13:42 +01:00
|
|
|
self.before: List[str] = []
|
|
|
|
self.after: List[str] = []
|
2019-01-22 19:25:00 +01:00
|
|
|
|
|
|
|
|
2020-12-15 05:38:52 +01:00
|
|
|
class RpcException(Exception):
|
|
|
|
# -32600 == "Invalid Request"
|
|
|
|
def __init__(self, message: str, code: int = -32600):
|
|
|
|
self.code = code
|
|
|
|
self.message = message
|
|
|
|
super().__init__("RpcException: {}".format(message))
|
|
|
|
|
|
|
|
|
2019-01-22 19:25:00 +01:00
|
|
|
class Request(dict):
|
|
|
|
"""A request object that wraps params and allows async return
|
|
|
|
"""
|
2020-06-26 16:39:02 +02:00
|
|
|
def __init__(self, plugin: 'Plugin', req_id: Optional[int], method: str,
|
|
|
|
params: Any, background: bool = False):
|
2019-01-22 19:25:00 +01:00
|
|
|
self.method = method
|
|
|
|
self.params = params
|
|
|
|
self.background = background
|
|
|
|
self.plugin = plugin
|
|
|
|
self.state = RequestState.PENDING
|
|
|
|
self.id = req_id
|
2020-09-25 16:43:14 +02:00
|
|
|
self.termination_tb: Optional[str] = None
|
2019-01-22 19:25:00 +01:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def getattr(self, key: str) -> Union[Method, Any, int]:
|
2019-01-22 19:25:00 +01:00
|
|
|
if key == "params":
|
|
|
|
return self.params
|
|
|
|
elif key == "id":
|
|
|
|
return self.id
|
|
|
|
elif key == "method":
|
|
|
|
return self.method
|
2020-06-26 16:39:02 +02:00
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
'Cannot get attribute "{key}" on Request'.format(key=key)
|
|
|
|
)
|
2019-01-22 19:25:00 +01:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def set_result(self, result: Any) -> None:
|
2019-01-22 19:25:00 +01:00
|
|
|
if self.state != RequestState.PENDING:
|
2020-09-25 16:43:14 +02:00
|
|
|
assert(self.termination_tb is not None)
|
2019-01-22 19:25:00 +01:00
|
|
|
raise ValueError(
|
|
|
|
"Cannot set the result of a request that is not pending, "
|
2020-09-25 16:43:14 +02:00
|
|
|
"current state is {state}. Request previously terminated at\n"
|
|
|
|
"{tb}".format(state=self.state, tb=self.termination_tb))
|
2019-01-22 19:25:00 +01:00
|
|
|
self.result = result
|
|
|
|
self._write_result({
|
|
|
|
'jsonrpc': '2.0',
|
|
|
|
'id': self.id,
|
|
|
|
'result': self.result
|
|
|
|
})
|
2020-09-25 16:43:14 +02:00
|
|
|
self.state = RequestState.FINISHED
|
|
|
|
self.termination_tb = "".join(traceback.extract_stack().format()[:-1])
|
2019-01-22 19:25:00 +01:00
|
|
|
|
2020-12-15 05:38:52 +01:00
|
|
|
def set_exception(self, exc: Union[Exception, RpcException]) -> None:
|
2019-01-22 19:25:00 +01:00
|
|
|
if self.state != RequestState.PENDING:
|
2020-09-25 16:43:14 +02:00
|
|
|
assert(self.termination_tb is not None)
|
2019-01-22 19:25:00 +01:00
|
|
|
raise ValueError(
|
|
|
|
"Cannot set the exception of a request that is not pending, "
|
2020-09-25 16:43:14 +02:00
|
|
|
"current state is {state}. Request previously terminated at\n"
|
|
|
|
"{tb}".format(state=self.state, tb=self.termination_tb))
|
2019-01-22 19:25:00 +01:00
|
|
|
self.exc = exc
|
2020-12-15 05:38:52 +01:00
|
|
|
if isinstance(exc, RpcException):
|
|
|
|
code = exc.code
|
|
|
|
message = exc.message
|
|
|
|
else:
|
|
|
|
code = -32600 # "Invalid Request"
|
|
|
|
message = ("Error while processing {method}: {exc}"
|
|
|
|
.format(method=self.method, exc=str(exc)))
|
2019-01-22 19:25:00 +01:00
|
|
|
self._write_result({
|
|
|
|
'jsonrpc': '2.0',
|
|
|
|
'id': self.id,
|
2020-04-10 00:47:01 +02:00
|
|
|
"error": {
|
2020-12-15 05:38:52 +01:00
|
|
|
"code": code,
|
|
|
|
"message": message,
|
2020-04-10 00:47:01 +02:00
|
|
|
# 'data' field "may be omitted."
|
2020-05-26 13:20:44 +02:00
|
|
|
"traceback": traceback.format_exc(),
|
2020-04-10 00:47:01 +02:00
|
|
|
},
|
2019-01-22 19:25:00 +01:00
|
|
|
})
|
2020-09-25 16:43:14 +02:00
|
|
|
self.state = RequestState.FAILED
|
|
|
|
self.termination_tb = "".join(traceback.extract_stack().format()[:-1])
|
2019-01-22 19:25:00 +01:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _write_result(self, result: dict) -> None:
|
2019-02-25 05:15:56 +01:00
|
|
|
self.plugin._write_locked(result)
|
2019-01-22 17:45:50 +01:00
|
|
|
|
2021-01-02 14:24:15 +01:00
|
|
|
def _notify(self, method: str, params: JSONType) -> None:
|
|
|
|
"""Send a notification to the caller.
|
|
|
|
|
|
|
|
Can contain a variety of things, but is usually used to report
|
|
|
|
progress or command status.
|
|
|
|
|
|
|
|
"""
|
|
|
|
self._write_result({
|
|
|
|
'jsonrpc': '2.0',
|
|
|
|
'params': params,
|
|
|
|
"method": method,
|
|
|
|
})
|
|
|
|
|
|
|
|
def notify(self, message: str, level: str = 'info') -> None:
|
|
|
|
"""Send a message notification to the caller.
|
|
|
|
"""
|
|
|
|
self._notify(
|
|
|
|
"message",
|
|
|
|
params={
|
|
|
|
'id': self.id,
|
|
|
|
'level': level,
|
|
|
|
'message': message,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
def progress(self,
|
|
|
|
progress: int,
|
|
|
|
total: int,
|
|
|
|
stage: Optional[int] = None,
|
|
|
|
stage_total: Optional[int] = None
|
|
|
|
) -> None:
|
|
|
|
d: Dict[str, JSONType] = {
|
|
|
|
"id": self.id,
|
|
|
|
"num": progress,
|
|
|
|
"total": total,
|
|
|
|
}
|
|
|
|
if stage is not None and stage_total is not None:
|
|
|
|
d['stage'] = {"num": stage, "total": stage_total}
|
|
|
|
|
|
|
|
self._notify("progress", d)
|
|
|
|
|
2019-01-22 17:45:50 +01:00
|
|
|
|
2020-09-09 14:37:28 +02:00
|
|
|
# If a hook call fails we need to coerce it into something the main daemon can
|
|
|
|
# handle. Returning an error is not an option since we explicitly do not allow
|
|
|
|
# those as a response to the calls, otherwise the only option we have is to
|
|
|
|
# crash the main daemon. The goal of these is to present a safe fallback
|
|
|
|
# should the hook call fail unexpectedly.
|
|
|
|
hook_fallbacks = {
|
|
|
|
'htlc_accepted': {
|
|
|
|
'result': 'fail',
|
|
|
|
'failure_message': '2002' # Fail with a temporary node failure
|
|
|
|
},
|
|
|
|
'peer_connected': {'result': 'continue'},
|
|
|
|
# commitment_revocation cannot recover from failing, let lightningd crash
|
|
|
|
# db_write cannot recover from failing, let lightningd crash
|
|
|
|
'invoice_payment': {'result': 'continue'},
|
|
|
|
'openchannel': {'result': 'reject'},
|
|
|
|
'rpc_command': {'result': 'continue'},
|
|
|
|
'custommsg': {'result': 'continue'},
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2018-12-10 15:38:21 +01:00
|
|
|
class Plugin(object):
|
|
|
|
"""Controls interactions with lightningd, and bundles functionality.
|
|
|
|
|
|
|
|
The Plugin class serves two purposes: it collects RPC methods and
|
|
|
|
options, and offers a control loop that dispatches incoming RPC
|
|
|
|
calls and hooks.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def __init__(self, stdout: Optional[io.TextIOBase] = None,
|
|
|
|
stdin: Optional[io.TextIOBase] = None, autopatch: bool = True,
|
|
|
|
dynamic: bool = True,
|
|
|
|
init_features: Optional[Union[int, str, bytes]] = None,
|
|
|
|
node_features: Optional[Union[int, str, bytes]] = None,
|
|
|
|
invoice_features: Optional[Union[int, str, bytes]] = None):
|
|
|
|
self.methods = {
|
|
|
|
'init': Method('init', self._init, MethodType.RPCMETHOD)
|
|
|
|
}
|
|
|
|
|
|
|
|
self.options: Dict[str, Dict[str, Any]] = {}
|
2021-04-27 15:15:09 +02:00
|
|
|
self.notification_topics: List[str] = []
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def convert_featurebits(
|
|
|
|
bits: Optional[Union[int, str, bytes]]) -> Optional[str]:
|
2020-01-29 17:02:47 +01:00
|
|
|
"""Convert the featurebits into the bytes required to hexencode.
|
|
|
|
"""
|
|
|
|
if bits is None:
|
|
|
|
return None
|
|
|
|
|
|
|
|
elif isinstance(bits, int):
|
|
|
|
bitlen = math.ceil(math.log(bits, 256))
|
|
|
|
return hexlify(bits.to_bytes(bitlen, 'big')).decode('ASCII')
|
|
|
|
|
|
|
|
elif isinstance(bits, str):
|
|
|
|
# Assume this is already hex encoded
|
|
|
|
return bits
|
|
|
|
|
|
|
|
elif isinstance(bits, bytes):
|
|
|
|
return hexlify(bits).decode('ASCII')
|
|
|
|
|
|
|
|
else:
|
2020-06-26 16:39:02 +02:00
|
|
|
raise ValueError(
|
|
|
|
"Could not convert featurebits to hex-encoded string"
|
|
|
|
)
|
2020-01-29 17:02:47 +01:00
|
|
|
|
|
|
|
self.featurebits = {
|
|
|
|
'init': convert_featurebits(init_features),
|
|
|
|
'node': convert_featurebits(node_features),
|
|
|
|
'invoice': convert_featurebits(invoice_features),
|
|
|
|
}
|
|
|
|
|
2018-12-11 18:24:55 +01:00
|
|
|
# A dict from topics to handler functions
|
2020-06-26 16:39:02 +02:00
|
|
|
self.subscriptions: Dict[str, Callable[..., None]] = {}
|
2018-12-11 18:24:55 +01:00
|
|
|
|
2018-12-10 15:38:21 +01:00
|
|
|
if not stdout:
|
|
|
|
self.stdout = sys.stdout
|
|
|
|
if not stdin:
|
|
|
|
self.stdin = sys.stdin
|
|
|
|
|
2019-08-23 12:28:06 +02:00
|
|
|
self.lightning_version = None
|
|
|
|
if os.getenv('LIGHTNINGD_VERSION'):
|
|
|
|
self.lightning_version = os.getenv('LIGHTNINGD_VERSION')
|
2018-12-10 15:38:21 +01:00
|
|
|
if os.getenv('LIGHTNINGD_PLUGIN') and autopatch:
|
|
|
|
monkey_patch(self, stdout=True, stderr=True)
|
|
|
|
|
2019-01-22 23:13:08 +01:00
|
|
|
self.add_method("getmanifest", self._getmanifest, background=False)
|
2020-06-26 16:39:02 +02:00
|
|
|
self.rpc_filename: Optional[str] = None
|
|
|
|
self.lightning_dir: Optional[str] = None
|
|
|
|
self.rpc: Optional[LightningRpc] = None
|
2019-07-18 14:20:37 +02:00
|
|
|
self.startup = True
|
|
|
|
self.dynamic = dynamic
|
2021-07-26 12:17:23 +02:00
|
|
|
|
|
|
|
# The function registering as init may return a dict of the
|
|
|
|
# form `{'disable': 'why'}` to self-disable, however most
|
|
|
|
# commonly you'll want to return `None`
|
|
|
|
self.child_init: Optional[Callable[..., Optional[dict]]] = None
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2019-01-22 19:25:00 +01:00
|
|
|
self.write_lock = RLock()
|
|
|
|
|
2020-09-29 11:26:25 +02:00
|
|
|
# Initialize the logging system with a handler that passes the logs to
|
|
|
|
# lightning for display.
|
|
|
|
log_handler = PluginLogHandler(self)
|
|
|
|
formatter = logging.Formatter('%(name)-12s: %(message)s')
|
|
|
|
log_handler.setFormatter(formatter)
|
|
|
|
logging.getLogger('').addHandler(log_handler)
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def add_method(self, name: str, func: Callable[..., Any],
|
|
|
|
background: bool = False,
|
|
|
|
category: Optional[str] = None,
|
|
|
|
desc: Optional[str] = None,
|
|
|
|
long_desc: Optional[str] = None,
|
|
|
|
deprecated: bool = False) -> None:
|
2018-12-10 15:38:21 +01:00
|
|
|
"""Add a plugin method to the dispatch table.
|
|
|
|
|
|
|
|
The function will be expected at call time (see `_dispatch`)
|
|
|
|
and the parameters from the JSON-RPC call will be mapped to
|
|
|
|
the function arguments. In addition to the parameters passed
|
|
|
|
from the JSON-RPC call we add a few that may be useful:
|
|
|
|
|
|
|
|
- `plugin`: gets a reference to this plugin.
|
|
|
|
|
|
|
|
- `request`: gets a reference to the raw request as a
|
|
|
|
dict. This corresponds to the JSON-RPC message that is
|
|
|
|
being dispatched.
|
|
|
|
|
|
|
|
Notice that due to the python binding logic we may be mapping
|
|
|
|
the arguments wrongly if we inject the plugin and/or request
|
|
|
|
in combination with positional binding. To prevent issues the
|
|
|
|
plugin and request argument should always be the last two
|
|
|
|
arguments and have a default on None.
|
|
|
|
|
2019-01-22 23:13:08 +01:00
|
|
|
The `background` argument can be used to specify whether the method is
|
|
|
|
going to return a result that should be sent back to the lightning
|
|
|
|
daemon (`background=False`) or whether the method will return without
|
|
|
|
sending back a result. In the latter case the method MUST use
|
|
|
|
`request.set_result` or `result.set_exception` to return a result or
|
|
|
|
raise an exception for the call.
|
|
|
|
|
2019-05-27 12:58:14 +02:00
|
|
|
The `category` argument can be used to specify the category of the
|
|
|
|
newly created rpc command.
|
|
|
|
|
2020-08-06 02:30:56 +02:00
|
|
|
`deprecated` means that it won't appear unless `allow-deprecated-apis`
|
|
|
|
is true (the default).
|
2018-12-10 15:38:21 +01:00
|
|
|
"""
|
|
|
|
if name in self.methods:
|
|
|
|
raise ValueError(
|
|
|
|
"Name {} is already bound to a method.".format(name)
|
|
|
|
)
|
|
|
|
|
|
|
|
# Register the function with the name
|
2020-06-26 16:39:02 +02:00
|
|
|
method = Method(
|
|
|
|
name, func, MethodType.RPCMETHOD, category, desc, long_desc,
|
|
|
|
deprecated
|
|
|
|
)
|
|
|
|
|
2019-01-22 23:13:08 +01:00
|
|
|
method.background = background
|
2019-01-22 17:45:50 +01:00
|
|
|
self.methods[name] = method
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def add_subscription(self, topic: str, func: Callable[..., None]) -> None:
|
2018-12-11 18:24:55 +01:00
|
|
|
"""Add a subscription to our list of subscriptions.
|
|
|
|
|
|
|
|
A subscription is an association between a topic and a handler
|
|
|
|
function. Adding a subscription means that we will
|
|
|
|
automatically subscribe to events from that topic with
|
|
|
|
`lightningd` and, upon receiving a matching notification, we
|
|
|
|
will call the associated handler. Notice that in order for the
|
|
|
|
automatic subscriptions to work, the handlers need to be
|
|
|
|
registered before we send our manifest, hence before
|
|
|
|
`Plugin.run` is called.
|
|
|
|
|
|
|
|
"""
|
|
|
|
if topic in self.subscriptions:
|
|
|
|
raise ValueError(
|
|
|
|
"Topic {} already has a handler".format(topic)
|
|
|
|
)
|
2019-08-05 02:19:48 +02:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
# Make sure the notification callback has a **kwargs argument so that
|
|
|
|
# it doesn't break if we add more arguments to the call later
|
|
|
|
# on. Issue a warning if it does not.
|
2019-08-05 02:19:48 +02:00
|
|
|
s = inspect.signature(func)
|
|
|
|
kinds = [p.kind for p in s.parameters.values()]
|
|
|
|
if inspect.Parameter.VAR_KEYWORD not in kinds:
|
|
|
|
self.log(
|
|
|
|
"Notification handler {} for notification {} does not have a "
|
|
|
|
"variable keyword argument. It is strongly suggested to add "
|
|
|
|
"`**kwargs` as last parameter to hook and notification "
|
|
|
|
"handlers.".format(func.__name__, topic), level="warn")
|
|
|
|
|
2018-12-11 18:24:55 +01:00
|
|
|
self.subscriptions[topic] = func
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def subscribe(self, topic: str) -> NoneDecoratorType:
|
2018-12-11 18:24:55 +01:00
|
|
|
"""Function decorator to register a notification handler.
|
2020-06-26 16:39:02 +02:00
|
|
|
|
2018-12-11 18:24:55 +01:00
|
|
|
"""
|
2020-06-26 16:39:02 +02:00
|
|
|
# Yes, decorator type annotations are just weird, don't think too much
|
|
|
|
# about it...
|
|
|
|
def decorator(f: Callable[..., None]) -> Callable[..., None]:
|
2018-12-11 18:24:55 +01:00
|
|
|
self.add_subscription(topic, f)
|
|
|
|
return f
|
|
|
|
return decorator
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def add_option(self, name: str, default: Optional[str],
|
|
|
|
description: Optional[str],
|
2020-12-14 05:52:23 +01:00
|
|
|
opt_type: str = "string", deprecated: bool = False,
|
|
|
|
multi: bool = False) -> None:
|
2018-12-10 15:59:31 +01:00
|
|
|
"""Add an option that we'd like to register with lightningd.
|
|
|
|
|
|
|
|
Needs to be called before `Plugin.run`, otherwise we might not
|
|
|
|
end up getting it set.
|
|
|
|
|
|
|
|
"""
|
|
|
|
if name in self.options:
|
|
|
|
raise ValueError(
|
|
|
|
"Name {} is already used by another option".format(name)
|
|
|
|
)
|
2019-05-25 18:13:24 +02:00
|
|
|
|
2020-03-17 02:34:35 +01:00
|
|
|
if opt_type not in ["string", "int", "bool", "flag"]:
|
2020-06-26 16:39:02 +02:00
|
|
|
raise ValueError(
|
|
|
|
'{} not in supported type set (string, int, bool, flag)'
|
|
|
|
)
|
2020-03-08 01:11:32 +01:00
|
|
|
|
2018-12-10 15:59:31 +01:00
|
|
|
self.options[name] = {
|
|
|
|
'name': name,
|
|
|
|
'default': default,
|
|
|
|
'description': description,
|
2019-05-25 18:13:24 +02:00
|
|
|
'type': opt_type,
|
2018-12-14 14:01:37 +01:00
|
|
|
'value': None,
|
2020-12-14 05:52:23 +01:00
|
|
|
'multi': multi,
|
2020-08-06 02:30:56 +02:00
|
|
|
'deprecated': deprecated,
|
2018-12-10 15:59:31 +01:00
|
|
|
}
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def add_flag_option(self, name: str, description: str,
|
|
|
|
deprecated: bool = False) -> None:
|
2020-03-17 02:34:35 +01:00
|
|
|
"""Add a flag option that we'd like to register with lightningd.
|
|
|
|
|
|
|
|
Needs to be called before `Plugin.run`, otherwise we might not
|
|
|
|
end up getting it set.
|
|
|
|
|
|
|
|
"""
|
2020-08-06 02:30:56 +02:00
|
|
|
self.add_option(name, None, description, opt_type="flag",
|
|
|
|
deprecated=deprecated)
|
2020-03-17 02:34:35 +01:00
|
|
|
|
2021-04-27 15:15:09 +02:00
|
|
|
def add_notification_topic(self, topic: str):
|
|
|
|
"""Announce that the plugin will emit notifications for the topic.
|
|
|
|
"""
|
|
|
|
self.notification_topics.append(topic)
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def get_option(self, name: str) -> str:
|
2018-12-14 14:01:37 +01:00
|
|
|
if name not in self.options:
|
2018-12-10 15:59:31 +01:00
|
|
|
raise ValueError("No option with name {} registered".format(name))
|
|
|
|
|
2018-12-14 14:01:37 +01:00
|
|
|
if self.options[name]['value'] is not None:
|
|
|
|
return self.options[name]['value']
|
|
|
|
else:
|
|
|
|
return self.options[name]['default']
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def async_method(self, method_name: str, category: Optional[str] = None,
|
|
|
|
desc: Optional[str] = None,
|
|
|
|
long_desc: Optional[str] = None,
|
|
|
|
deprecated: bool = False) -> NoneDecoratorType:
|
2019-02-21 15:22:07 +01:00
|
|
|
"""Decorator to add an async plugin method to the dispatch table.
|
|
|
|
|
|
|
|
Internally uses add_method.
|
|
|
|
"""
|
2020-06-26 16:39:02 +02:00
|
|
|
def decorator(f: Callable[..., None]) -> Callable[..., None]:
|
2019-06-30 18:30:05 +02:00
|
|
|
self.add_method(method_name, f, background=True, category=category,
|
2020-08-06 02:30:56 +02:00
|
|
|
desc=desc, long_desc=long_desc,
|
|
|
|
deprecated=deprecated)
|
2019-02-21 15:22:07 +01:00
|
|
|
return f
|
|
|
|
return decorator
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def method(self, method_name: str, category: Optional[str] = None,
|
|
|
|
desc: Optional[str] = None,
|
|
|
|
long_desc: Optional[str] = None,
|
|
|
|
deprecated: bool = False) -> JsonDecoratorType:
|
2018-12-10 15:38:21 +01:00
|
|
|
"""Decorator to add a plugin method to the dispatch table.
|
|
|
|
|
|
|
|
Internally uses add_method.
|
|
|
|
"""
|
2020-06-26 16:39:02 +02:00
|
|
|
def decorator(f: Callable[..., JSONType]) -> Callable[..., JSONType]:
|
|
|
|
self.add_method(method_name,
|
|
|
|
f,
|
|
|
|
background=False,
|
|
|
|
category=category,
|
|
|
|
desc=desc,
|
|
|
|
long_desc=long_desc,
|
2020-08-06 02:30:56 +02:00
|
|
|
deprecated=deprecated)
|
2018-12-10 15:38:21 +01:00
|
|
|
return f
|
|
|
|
return decorator
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def add_hook(self, name: str, func: Callable[..., JSONType],
|
2020-10-30 02:13:42 +01:00
|
|
|
background: bool = False,
|
|
|
|
before: Optional[List[str]] = None,
|
|
|
|
after: Optional[List[str]] = None) -> None:
|
2018-12-18 17:32:16 +01:00
|
|
|
"""Register a hook that is called synchronously by lightningd on events
|
|
|
|
"""
|
|
|
|
if name in self.methods:
|
|
|
|
raise ValueError(
|
2020-06-26 13:20:35 +02:00
|
|
|
"Method {name} was already registered".format(name=name)
|
2018-12-18 17:32:16 +01:00
|
|
|
)
|
2019-08-05 02:19:48 +02:00
|
|
|
|
|
|
|
# Make sure the hook callback has a **kwargs argument so that it
|
|
|
|
# doesn't break if we add more arguments to the call later on. Issue a
|
|
|
|
# warning if it does not.
|
|
|
|
s = inspect.signature(func)
|
|
|
|
kinds = [p.kind for p in s.parameters.values()]
|
|
|
|
if inspect.Parameter.VAR_KEYWORD not in kinds:
|
|
|
|
self.log(
|
|
|
|
"Hook handler {} for hook {} does not have a variable keyword "
|
|
|
|
"argument. It is strongly suggested to add `**kwargs` as last "
|
|
|
|
"parameter to hook and notification handlers.".format(
|
|
|
|
func.__name__, name), level="warn")
|
|
|
|
|
2019-01-22 17:45:50 +01:00
|
|
|
method = Method(name, func, MethodType.HOOK)
|
2019-01-22 23:13:08 +01:00
|
|
|
method.background = background
|
2020-10-30 02:13:42 +01:00
|
|
|
method.before = []
|
|
|
|
if before:
|
|
|
|
method.before = before
|
|
|
|
method.after = []
|
|
|
|
if after:
|
|
|
|
method.after = after
|
2019-01-22 17:45:50 +01:00
|
|
|
self.methods[name] = method
|
2018-12-18 17:32:16 +01:00
|
|
|
|
2020-10-30 02:13:42 +01:00
|
|
|
def hook(self, method_name: str,
|
|
|
|
before: List[str] = None,
|
|
|
|
after: List[str] = None) -> JsonDecoratorType:
|
2018-12-18 17:32:16 +01:00
|
|
|
"""Decorator to add a plugin hook to the dispatch table.
|
|
|
|
|
|
|
|
Internally uses add_hook.
|
|
|
|
"""
|
2020-06-26 16:39:02 +02:00
|
|
|
def decorator(f: Callable[..., JSONType]) -> Callable[..., JSONType]:
|
2020-10-30 02:13:42 +01:00
|
|
|
self.add_hook(method_name, f, background=False, before=before, after=after)
|
2019-02-21 15:22:07 +01:00
|
|
|
return f
|
|
|
|
return decorator
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def async_hook(self, method_name: str) -> NoneDecoratorType:
|
2019-02-21 15:22:07 +01:00
|
|
|
"""Decorator to add an async plugin hook to the dispatch table.
|
|
|
|
|
|
|
|
Internally uses add_hook.
|
|
|
|
"""
|
2020-06-26 16:39:02 +02:00
|
|
|
def decorator(f: Callable[..., None]) -> Callable[..., None]:
|
2019-02-21 15:22:07 +01:00
|
|
|
self.add_hook(method_name, f, background=True)
|
2018-12-18 17:32:16 +01:00
|
|
|
return f
|
|
|
|
return decorator
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def init(self) -> NoneDecoratorType:
|
2019-02-04 11:55:42 +01:00
|
|
|
"""Decorator to add a function called after plugin initialization
|
|
|
|
"""
|
2020-06-26 16:39:02 +02:00
|
|
|
def decorator(f: Callable[..., None]) -> Callable[..., None]:
|
2019-02-04 11:55:42 +01:00
|
|
|
if self.child_init is not None:
|
2020-06-26 16:39:02 +02:00
|
|
|
raise ValueError(
|
|
|
|
'The @plugin.init decorator should only be used once'
|
|
|
|
)
|
2019-02-04 11:55:42 +01:00
|
|
|
self.child_init = f
|
|
|
|
return f
|
|
|
|
return decorator
|
|
|
|
|
2019-05-08 13:17:14 +02:00
|
|
|
@staticmethod
|
2020-06-26 16:39:02 +02:00
|
|
|
def _coerce_arguments(
|
|
|
|
func: Callable[..., Any],
|
|
|
|
ba: inspect.BoundArguments) -> inspect.BoundArguments:
|
2019-05-08 13:17:14 +02:00
|
|
|
args = OrderedDict()
|
2020-06-26 16:39:02 +02:00
|
|
|
annotations = {}
|
|
|
|
if hasattr(func, "__annotations__"):
|
|
|
|
annotations = func.__annotations__
|
|
|
|
|
2019-05-08 13:17:14 +02:00
|
|
|
for key, val in ba.arguments.items():
|
2019-12-15 20:10:40 +01:00
|
|
|
annotation = annotations.get(key, None)
|
|
|
|
if annotation is not None and annotation == Millisatoshi:
|
2019-05-08 13:17:14 +02:00
|
|
|
args[key] = Millisatoshi(val)
|
|
|
|
else:
|
|
|
|
args[key] = val
|
|
|
|
ba.arguments = args
|
|
|
|
return ba
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _bind_pos(self, func: Callable[..., Any], params: List[str],
|
|
|
|
request: Request) -> inspect.BoundArguments:
|
2019-05-08 13:17:14 +02:00
|
|
|
"""Positional binding of parameters
|
|
|
|
"""
|
|
|
|
assert(isinstance(params, list))
|
2018-12-10 15:38:21 +01:00
|
|
|
sig = inspect.signature(func)
|
|
|
|
|
2019-05-08 13:17:14 +02:00
|
|
|
# Collect injections so we can sort them and insert them in the right
|
|
|
|
# order later. If we don't apply inject them in increasing order we
|
|
|
|
# might shift away an earlier injection.
|
2020-06-26 16:39:02 +02:00
|
|
|
injections: List[Tuple[int, Any]] = []
|
2019-05-08 13:17:14 +02:00
|
|
|
if 'plugin' in sig.parameters:
|
|
|
|
pos = list(sig.parameters.keys()).index('plugin')
|
|
|
|
injections.append((pos, self))
|
|
|
|
if 'request' in sig.parameters:
|
|
|
|
pos = list(sig.parameters.keys()).index('request')
|
|
|
|
injections.append((pos, request))
|
|
|
|
injections = sorted(injections)
|
|
|
|
for pos, val in injections:
|
|
|
|
params = params[:pos] + [val] + params[pos:]
|
|
|
|
|
|
|
|
ba = sig.bind(*params)
|
|
|
|
self._coerce_arguments(func, ba)
|
2018-12-10 15:38:21 +01:00
|
|
|
ba.apply_defaults()
|
2019-05-08 13:17:14 +02:00
|
|
|
return ba
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _bind_kwargs(self, func: Callable[..., Any], params: Dict[str, Any],
|
|
|
|
request: Request) -> inspect.BoundArguments:
|
2019-05-08 13:17:14 +02:00
|
|
|
"""Keyword based binding of parameters
|
|
|
|
"""
|
|
|
|
assert(isinstance(params, dict))
|
|
|
|
sig = inspect.signature(func)
|
|
|
|
|
|
|
|
# Inject additional parameters if they are in the signature.
|
|
|
|
if 'plugin' in sig.parameters:
|
|
|
|
params['plugin'] = self
|
|
|
|
elif 'plugin' in params:
|
|
|
|
del params['plugin']
|
|
|
|
if 'request' in sig.parameters:
|
|
|
|
params['request'] = request
|
|
|
|
elif 'request' in params:
|
|
|
|
del params['request']
|
|
|
|
|
|
|
|
ba = sig.bind(**params)
|
|
|
|
self._coerce_arguments(func, ba)
|
|
|
|
return ba
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _exec_func(self, func: Callable[..., Any],
|
|
|
|
request: Request) -> JSONType:
|
2019-05-08 13:17:14 +02:00
|
|
|
params = request.params
|
|
|
|
if isinstance(params, list):
|
|
|
|
ba = self._bind_pos(func, params, request)
|
|
|
|
return func(*ba.args, **ba.kwargs)
|
|
|
|
elif isinstance(params, dict):
|
|
|
|
ba = self._bind_kwargs(func, params, request)
|
|
|
|
return func(*ba.args, **ba.kwargs)
|
|
|
|
else:
|
2020-06-26 16:39:02 +02:00
|
|
|
raise TypeError(
|
|
|
|
"Parameters to function call must be either a dict or a list."
|
|
|
|
)
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _dispatch_request(self, request: Request) -> None:
|
2019-01-22 19:25:00 +01:00
|
|
|
name = request.method
|
2018-12-11 18:24:55 +01:00
|
|
|
|
|
|
|
if name not in self.methods:
|
|
|
|
raise ValueError("No method {} found.".format(name))
|
2019-01-22 17:45:50 +01:00
|
|
|
method = self.methods[name]
|
2019-01-22 19:25:00 +01:00
|
|
|
request.background = method.background
|
2018-12-11 18:24:55 +01:00
|
|
|
|
|
|
|
try:
|
2019-01-22 19:25:00 +01:00
|
|
|
result = self._exec_func(method.func, request)
|
|
|
|
if not method.background:
|
2021-09-04 11:51:50 +02:00
|
|
|
# Only if this is a synchronous (background=False) call do we need to
|
|
|
|
# return the result. Otherwise the callee (method) will eventually need
|
2019-01-22 19:25:00 +01:00
|
|
|
# to call request.set_result or request.set_exception to
|
|
|
|
# return a result or raise an exception.
|
|
|
|
request.set_result(result)
|
2018-12-11 18:24:55 +01:00
|
|
|
except Exception as e:
|
2020-09-09 14:37:28 +02:00
|
|
|
if name in hook_fallbacks:
|
|
|
|
response = hook_fallbacks[name]
|
|
|
|
self.log((
|
|
|
|
"Hook handler for {name} failed with an exception. "
|
|
|
|
"Returning safe fallback response {response} to avoid "
|
|
|
|
"crashing the main daemon. Please contact the plugin "
|
|
|
|
"author!"
|
|
|
|
).format(name=name, response=response), level="error")
|
|
|
|
|
|
|
|
request.set_result(response)
|
|
|
|
else:
|
|
|
|
request.set_exception(e)
|
2018-12-11 18:24:55 +01:00
|
|
|
self.log(traceback.format_exc())
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _dispatch_notification(self, request: Request) -> None:
|
2019-01-22 19:25:00 +01:00
|
|
|
if request.method not in self.subscriptions:
|
|
|
|
raise ValueError("No subscription for {name} found.".format(
|
|
|
|
name=request.method))
|
|
|
|
func = self.subscriptions[request.method]
|
2018-12-11 18:24:55 +01:00
|
|
|
|
|
|
|
try:
|
|
|
|
self._exec_func(func, request)
|
2019-01-25 03:51:54 +01:00
|
|
|
except Exception:
|
2018-12-11 18:24:55 +01:00
|
|
|
self.log(traceback.format_exc())
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _write_locked(self, obj: JSONType) -> None:
|
2019-03-04 04:00:35 +01:00
|
|
|
# ensure_ascii turns UTF-8 into \uXXXX so we need to suppress that,
|
|
|
|
# then utf8 ourselves.
|
2020-06-26 16:39:02 +02:00
|
|
|
s = bytes(json.dumps(
|
|
|
|
obj,
|
|
|
|
cls=LightningRpc.LightningJSONEncoder,
|
|
|
|
ensure_ascii=False
|
|
|
|
) + "\n\n", encoding='utf-8')
|
2019-02-25 05:15:56 +01:00
|
|
|
with self.write_lock:
|
2019-03-04 04:00:35 +01:00
|
|
|
self.stdout.buffer.write(s)
|
2019-02-25 05:15:56 +01:00
|
|
|
self.stdout.flush()
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def notify(self, method: str, params: JSONType) -> None:
|
2018-12-10 15:38:21 +01:00
|
|
|
payload = {
|
|
|
|
'jsonrpc': '2.0',
|
|
|
|
'method': method,
|
|
|
|
'params': params,
|
|
|
|
}
|
2019-02-25 05:15:56 +01:00
|
|
|
self._write_locked(payload)
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def log(self, message: str, level: str = 'info') -> None:
|
2018-12-10 16:41:42 +01:00
|
|
|
# Split the log into multiple lines and print them
|
|
|
|
# individually. Makes tracebacks much easier to read.
|
|
|
|
for line in message.split('\n'):
|
|
|
|
self.notify('log', {'level': level, 'message': line})
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2020-10-12 07:33:50 +02:00
|
|
|
def notify_message(self, request: Request, message: str,
|
|
|
|
level: str = 'info') -> None:
|
|
|
|
"""Send a notification message to sender of this request"""
|
2021-01-02 14:24:15 +01:00
|
|
|
request.notify(message=message)
|
2020-10-12 07:33:50 +02:00
|
|
|
|
|
|
|
def notify_progress(self, request: Request,
|
|
|
|
progress: int, progress_total: int,
|
|
|
|
stage: Optional[int] = None,
|
|
|
|
stage_total: Optional[int] = None) -> None:
|
2021-01-02 14:24:15 +01:00
|
|
|
"""Send a progress message to sender of this request: if more than one stage, set stage and stage_total"""
|
|
|
|
request.progress(progress, progress_total, stage, stage_total)
|
2020-10-12 07:33:50 +02:00
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _parse_request(self, jsrequest: Dict[str, JSONType]) -> Request:
|
|
|
|
i = jsrequest.get('id', None)
|
|
|
|
if not isinstance(i, int) and i is not None:
|
|
|
|
raise ValueError('Non-integer request id "{i}"'.format(i=i))
|
|
|
|
|
2019-02-21 18:59:15 +01:00
|
|
|
request = Request(
|
|
|
|
plugin=self,
|
2020-06-26 16:39:02 +02:00
|
|
|
req_id=i,
|
|
|
|
method=str(jsrequest['method']),
|
2019-02-21 18:59:15 +01:00
|
|
|
params=jsrequest['params'],
|
|
|
|
background=False,
|
|
|
|
)
|
|
|
|
return request
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _multi_dispatch(self, msgs: List[bytes]) -> bytes:
|
2018-12-10 15:38:21 +01:00
|
|
|
"""We received a couple of messages, now try to dispatch them all.
|
|
|
|
|
|
|
|
Returns the last partial message that was not complete yet.
|
|
|
|
"""
|
|
|
|
for payload in msgs[:-1]:
|
2020-06-26 16:39:02 +02:00
|
|
|
# Note that we use function annotations to do Millisatoshi
|
|
|
|
# conversions in _exec_func, so we don't use LightningJSONDecoder
|
|
|
|
# here.
|
2019-03-04 04:00:35 +01:00
|
|
|
request = self._parse_request(json.loads(payload.decode('utf8')))
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2018-12-11 18:24:55 +01:00
|
|
|
# If this has an 'id'-field, it's a request and returns a
|
|
|
|
# result. Otherwise it's a notification and it doesn't
|
|
|
|
# return anything.
|
2019-01-22 19:25:00 +01:00
|
|
|
if request.id is not None:
|
2018-12-11 18:24:55 +01:00
|
|
|
self._dispatch_request(request)
|
|
|
|
else:
|
|
|
|
self._dispatch_notification(request)
|
|
|
|
|
2018-12-10 15:38:21 +01:00
|
|
|
return msgs[-1]
|
|
|
|
|
2021-03-09 18:04:55 +01:00
|
|
|
def print_usage(self):
|
|
|
|
import textwrap
|
|
|
|
|
|
|
|
executable = os.path.abspath(sys.argv[0])
|
|
|
|
overview = textwrap.dedent("""
|
|
|
|
Hi, it looks like you're trying to run a plugin from the
|
|
|
|
command line. Plugins are usually started and controlled by
|
|
|
|
lightningd, which allows you to simply specify which plugins
|
|
|
|
you'd like to run using the --plugin command line option when
|
|
|
|
starting lightningd. The following is an example of how that'd
|
|
|
|
look:
|
|
|
|
|
|
|
|
$ lightningd --plugin={executable}
|
|
|
|
|
2021-06-17 12:52:20 +02:00
|
|
|
If lightningd is already running, you can also start a plugin
|
|
|
|
by using the cli:
|
|
|
|
|
|
|
|
$ lightning-cli plugin start /path/to/a/plugin
|
|
|
|
|
2021-03-09 18:04:55 +01:00
|
|
|
Since we're here however let me tell you about this plugin.
|
|
|
|
""").format(executable=executable)
|
|
|
|
|
|
|
|
methods_header = textwrap.dedent("""
|
|
|
|
|
|
|
|
RPC methods
|
|
|
|
===========
|
|
|
|
|
|
|
|
Plugins may provide additional RPC methods that you can simply
|
|
|
|
call as if they were built-in methods from lightningd
|
|
|
|
itself. To call them just use lightning-cli or any other
|
|
|
|
frontend. The following methods are defined by this plugin:
|
|
|
|
""")
|
|
|
|
|
|
|
|
parts = [overview]
|
|
|
|
|
|
|
|
method_tpl = textwrap.dedent("""
|
|
|
|
{name}
|
|
|
|
{doc}
|
|
|
|
""")
|
|
|
|
|
|
|
|
for method in self.methods.values():
|
|
|
|
if method.name in ['init', 'getmanifest']:
|
|
|
|
# Skip internal methods provided by all plugins
|
|
|
|
continue
|
|
|
|
|
|
|
|
if method.mtype != MethodType.RPCMETHOD:
|
|
|
|
# Don't include non-rpc-methods in the rpc-method
|
|
|
|
# section
|
|
|
|
continue
|
|
|
|
|
|
|
|
if methods_header is not None:
|
|
|
|
# Listen carefully, I shall say this only once :-)
|
|
|
|
parts.append(methods_header)
|
|
|
|
methods_header = None
|
|
|
|
|
|
|
|
doc = method.long_desc if method.long_desc is not None else "No documentation found"
|
|
|
|
parts.append(method_tpl.format(
|
|
|
|
name=method.name,
|
|
|
|
doc=textwrap.indent(doc, prefix=" ")
|
|
|
|
))
|
|
|
|
|
|
|
|
options_header = textwrap.dedent("""
|
|
|
|
Command line options
|
|
|
|
====================
|
|
|
|
|
|
|
|
This plugin exposes the following command line options. They
|
|
|
|
can be specified just like any other you might gice lightning
|
|
|
|
at startup. The following options are exposed by this plugin:
|
|
|
|
""")
|
|
|
|
|
|
|
|
option_tpl = textwrap.dedent("""
|
|
|
|
--{name}={typ} (default: {default}
|
|
|
|
{doc}
|
|
|
|
""")
|
|
|
|
for opt in self.options.values():
|
|
|
|
if options_header is not None:
|
|
|
|
parts.append(options_header)
|
|
|
|
options_header = None
|
|
|
|
|
|
|
|
doc = textwrap.indent(opt['description'], prefix=" ")
|
|
|
|
|
|
|
|
if opt['multi']:
|
|
|
|
doc += "\n\n This option can be specified multiple times"
|
|
|
|
|
|
|
|
parts.append(option_tpl.format(
|
|
|
|
name=opt['name'],
|
|
|
|
doc=doc,
|
|
|
|
default=opt['default'],
|
|
|
|
typ=opt['type'],
|
|
|
|
))
|
|
|
|
|
|
|
|
sys.stdout.write("".join(parts))
|
|
|
|
sys.stdout.write("\n")
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def run(self) -> None:
|
2021-03-09 18:04:55 +01:00
|
|
|
# If we are not running inside lightningd we'll print usage
|
|
|
|
# and some information about the plugin.
|
|
|
|
if os.environ.get('LIGHTNINGD_PLUGIN', None) != '1':
|
|
|
|
return self.print_usage()
|
|
|
|
|
2019-03-04 04:00:35 +01:00
|
|
|
partial = b""
|
|
|
|
for l in self.stdin.buffer:
|
2018-12-10 15:38:21 +01:00
|
|
|
partial += l
|
|
|
|
|
2019-03-04 04:00:35 +01:00
|
|
|
msgs = partial.split(b'\n\n')
|
2018-12-10 15:38:21 +01:00
|
|
|
if len(msgs) < 2:
|
|
|
|
continue
|
|
|
|
|
|
|
|
partial = self._multi_dispatch(msgs)
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _getmanifest(self, **kwargs) -> JSONType:
|
2020-08-06 02:27:56 +02:00
|
|
|
if 'allow-deprecated-apis' in kwargs:
|
|
|
|
self.deprecated_apis = kwargs['allow-deprecated-apis']
|
|
|
|
else:
|
|
|
|
# 0.9.0 and before didn't offer this, so assume "yes".
|
|
|
|
self.deprecated_apis = True
|
|
|
|
|
2018-12-10 15:38:21 +01:00
|
|
|
methods = []
|
2018-12-18 17:32:16 +01:00
|
|
|
hooks = []
|
2019-01-22 17:45:50 +01:00
|
|
|
for method in self.methods.values():
|
2018-12-10 15:38:21 +01:00
|
|
|
# Skip the builtin ones, they don't get reported
|
2019-01-22 17:45:50 +01:00
|
|
|
if method.name in ['getmanifest', 'init']:
|
2018-12-10 15:38:21 +01:00
|
|
|
continue
|
|
|
|
|
2019-01-22 17:45:50 +01:00
|
|
|
if method.mtype == MethodType.HOOK:
|
2020-10-30 02:13:42 +01:00
|
|
|
hooks.append({'name': method.name,
|
|
|
|
'before': method.before,
|
|
|
|
'after': method.after})
|
2018-12-18 17:32:16 +01:00
|
|
|
continue
|
|
|
|
|
2019-01-22 17:45:50 +01:00
|
|
|
doc = inspect.getdoc(method.func)
|
2018-12-10 15:38:21 +01:00
|
|
|
if not doc:
|
|
|
|
self.log(
|
2020-06-26 16:39:02 +02:00
|
|
|
'RPC method \'{}\' does not have a docstring.'.format(
|
|
|
|
method.name
|
|
|
|
)
|
2018-12-10 15:38:21 +01:00
|
|
|
)
|
|
|
|
doc = "Undocumented RPC method from a plugin."
|
2019-01-08 19:24:33 +01:00
|
|
|
doc = re.sub('\n+', ' ', doc)
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2019-02-07 04:14:53 +01:00
|
|
|
# Handles out-of-order use of parameters like:
|
2020-06-26 16:39:02 +02:00
|
|
|
#
|
|
|
|
# ```python3
|
|
|
|
#
|
|
|
|
# def hello_obfus(arg1, arg2, plugin, thing3, request=None,
|
|
|
|
# thing5='at', thing6=21)
|
|
|
|
#
|
|
|
|
# ```
|
2019-02-25 05:15:56 +01:00
|
|
|
argspec = inspect.getfullargspec(method.func)
|
2019-02-05 01:16:47 +01:00
|
|
|
defaults = argspec.defaults
|
2019-02-07 04:14:53 +01:00
|
|
|
num_defaults = len(defaults) if defaults else 0
|
|
|
|
start_kwargs_idx = len(argspec.args) - num_defaults
|
|
|
|
args = []
|
|
|
|
for idx, arg in enumerate(argspec.args):
|
|
|
|
if arg in ('plugin', 'request'):
|
|
|
|
continue
|
|
|
|
# Positional arg
|
|
|
|
if idx < start_kwargs_idx:
|
|
|
|
args.append("%s" % arg)
|
|
|
|
# Keyword arg
|
|
|
|
else:
|
|
|
|
args.append("[%s]" % arg)
|
2019-02-05 01:16:47 +01:00
|
|
|
|
2018-12-10 15:38:21 +01:00
|
|
|
methods.append({
|
2019-01-22 17:45:50 +01:00
|
|
|
'name': method.name,
|
2019-05-27 12:58:14 +02:00
|
|
|
'category': method.category if method.category else "plugin",
|
2019-02-05 01:16:47 +01:00
|
|
|
'usage': " ".join(args),
|
2019-06-30 18:30:05 +02:00
|
|
|
'description': doc if not method.desc else method.desc
|
2018-12-10 15:38:21 +01:00
|
|
|
})
|
2019-06-30 18:30:05 +02:00
|
|
|
if method.long_desc:
|
2020-06-26 16:39:02 +02:00
|
|
|
m = methods[len(methods) - 1]
|
|
|
|
m["long_description"] = method.long_desc
|
2018-12-10 15:38:21 +01:00
|
|
|
|
2020-01-29 17:02:47 +01:00
|
|
|
manifest = {
|
2018-12-10 15:59:31 +01:00
|
|
|
'options': list(self.options.values()),
|
2018-12-10 15:38:21 +01:00
|
|
|
'rpcmethods': methods,
|
2018-12-11 18:24:55 +01:00
|
|
|
'subscriptions': list(self.subscriptions.keys()),
|
2018-12-18 17:32:16 +01:00
|
|
|
'hooks': hooks,
|
2020-01-29 17:02:47 +01:00
|
|
|
'dynamic': self.dynamic,
|
2021-04-27 15:15:09 +02:00
|
|
|
'notifications': [
|
|
|
|
{"method": name} for name in self.notification_topics
|
|
|
|
],
|
2018-12-10 15:38:21 +01:00
|
|
|
}
|
|
|
|
|
2020-01-29 17:02:47 +01:00
|
|
|
# Compact the features a bit, not important.
|
|
|
|
features = {k: v for k, v in self.featurebits.items() if v is not None}
|
|
|
|
if features is not None:
|
|
|
|
manifest['featurebits'] = features
|
|
|
|
|
|
|
|
return manifest
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def _init(self, options: Dict[str, JSONType],
|
|
|
|
configuration: Dict[str, JSONType],
|
|
|
|
request: Request) -> JSONType:
|
|
|
|
|
|
|
|
def verify_str(d: Dict[str, JSONType], key: str) -> str:
|
|
|
|
v = d.get(key)
|
|
|
|
if not isinstance(v, str):
|
|
|
|
raise ValueError("Wrong argument to init: expected {key} to be"
|
|
|
|
" a string, got {v}".format(key=key, v=v))
|
|
|
|
return v
|
|
|
|
|
|
|
|
def verify_bool(d: Dict[str, JSONType], key: str) -> bool:
|
|
|
|
v = d.get(key)
|
|
|
|
if not isinstance(v, bool):
|
|
|
|
raise ValueError("Wrong argument to init: expected {key} to be"
|
|
|
|
" a bool, got {v}".format(key=key, v=v))
|
|
|
|
return v
|
|
|
|
|
|
|
|
self.rpc_filename = verify_str(configuration, 'rpc-file')
|
|
|
|
self.lightning_dir = verify_str(configuration, 'lightning-dir')
|
|
|
|
|
2019-01-03 20:23:02 +01:00
|
|
|
path = os.path.join(self.lightning_dir, self.rpc_filename)
|
|
|
|
self.rpc = LightningRpc(path)
|
2020-06-26 16:39:02 +02:00
|
|
|
self.startup = verify_bool(configuration, 'startup')
|
2018-12-10 15:59:31 +01:00
|
|
|
for name, value in options.items():
|
2018-12-14 14:01:37 +01:00
|
|
|
self.options[name]['value'] = value
|
2018-12-10 15:59:31 +01:00
|
|
|
|
2019-02-04 11:55:42 +01:00
|
|
|
# Dispatch the plugin's init handler if any
|
|
|
|
if self.child_init:
|
|
|
|
return self._exec_func(self.child_init, request)
|
2018-12-10 15:38:21 +01:00
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
class PluginStream(object):
|
|
|
|
"""Sink that turns everything that is written to it into a notification.
|
|
|
|
"""
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def __init__(self, plugin: Plugin, level: str = "info"):
|
2018-12-10 15:38:21 +01:00
|
|
|
self.plugin = plugin
|
|
|
|
self.level = level
|
|
|
|
self.buff = ''
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def write(self, payload: str) -> None:
|
2018-12-10 15:38:21 +01:00
|
|
|
self.buff += payload
|
|
|
|
|
2019-01-21 18:28:33 +01:00
|
|
|
if len(payload) > 0 and payload[-1] == '\n':
|
2018-12-10 15:38:21 +01:00
|
|
|
self.flush()
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def flush(self) -> None:
|
2018-12-10 15:38:21 +01:00
|
|
|
lines = self.buff.split('\n')
|
|
|
|
if len(lines) < 2:
|
|
|
|
return
|
|
|
|
|
|
|
|
for l in lines[:-1]:
|
|
|
|
self.plugin.log(l, self.level)
|
|
|
|
|
|
|
|
# lines[-1] is either an empty string or a partial line
|
|
|
|
self.buff = lines[-1]
|
|
|
|
|
|
|
|
|
2020-06-26 16:39:02 +02:00
|
|
|
def monkey_patch(plugin: Plugin, stdout: bool = True,
|
|
|
|
stderr: bool = False) -> None:
|
2018-12-10 15:38:21 +01:00
|
|
|
"""Monkey patch stderr and stdout so we use notifications instead.
|
|
|
|
|
|
|
|
A plugin commonly communicates with lightningd over its stdout and
|
|
|
|
stdin filedescriptor, so if we use them in some other way
|
|
|
|
(printing, logging, ...) we're breaking our communication
|
|
|
|
channel. This function monkey patches these streams in the `sys`
|
|
|
|
module to be redirected to a `PluginStream` which wraps anything
|
|
|
|
that would get written to these streams into valid log
|
|
|
|
notifications that can be interpreted and printed by `lightningd`.
|
|
|
|
|
|
|
|
"""
|
|
|
|
if stdout:
|
|
|
|
setattr(sys, "stdout", PluginStream(plugin, level="info"))
|
|
|
|
if stderr:
|
|
|
|
setattr(sys, "stderr", PluginStream(plugin, level="warn"))
|
2020-09-29 11:26:25 +02:00
|
|
|
|
|
|
|
|
|
|
|
class PluginLogHandler(logging.StreamHandler):
|
|
|
|
def __init__(self, plugin: Plugin) -> None:
|
|
|
|
logging.StreamHandler.__init__(self, stream=None)
|
|
|
|
self.plugin = plugin
|
|
|
|
|
|
|
|
# Map the numeric levels to the string levels lightningd understands.
|
|
|
|
self.levels = {
|
|
|
|
logging.CRITICAL: 'error',
|
|
|
|
logging.ERROR: 'error',
|
|
|
|
logging.WARNING: 'info',
|
|
|
|
logging.INFO: 'info',
|
|
|
|
logging.DEBUG: 'debug',
|
|
|
|
logging.NOTSET: 'debug',
|
|
|
|
}
|
|
|
|
|
|
|
|
def emit(self, record: logging.LogRecord) -> None:
|
|
|
|
"""Emit a record.
|
|
|
|
|
|
|
|
If a formatter is specified, it is used to format the record. Numeric
|
|
|
|
levels are translated into strings that lightningd understands. If
|
|
|
|
exception information is present, it is formatted using
|
|
|
|
traceback.print_exception and appended to the stream.
|
|
|
|
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
msg = self.format(record)
|
|
|
|
level = self.levels.get(record.levelno, 'info')
|
|
|
|
self.plugin.log(msg, level=level)
|
|
|
|
except RecursionError: # See issue https://bugs.python.org/issue36272
|
|
|
|
raise
|
|
|
|
except Exception:
|
|
|
|
self.handleError(record) # Writes errors in logging system to stderr
|
|
|
|
pass
|
|
|
|
|
|
|
|
def flush(self) -> None:
|
|
|
|
"""Flushing is a no-op since each message is written as it comes in.
|
|
|
|
"""
|
|
|
|
pass
|