From 9ad2f57e469ea7b6c97e3b33b882159399427655 Mon Sep 17 00:00:00 2001 From: Christian Decker Date: Tue, 11 Dec 2018 18:14:15 +0100 Subject: [PATCH] jsonrpc: Create a struct for notifications that we send Signed-off-by: Christian Decker --- lightningd/jsonrpc.c | 20 ++++++++++++++++++++ lightningd/jsonrpc.h | 21 +++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/lightningd/jsonrpc.c b/lightningd/jsonrpc.c index 568005e27..89a4dfdd5 100644 --- a/lightningd/jsonrpc.c +++ b/lightningd/jsonrpc.c @@ -1004,6 +1004,26 @@ static struct command_result *param_command(struct command *cmd, tok->end - tok->start, buffer + tok->start); } +struct jsonrpc_notification *jsonrpc_notification_start(const tal_t *ctx, const char *method) +{ + struct jsonrpc_notification *n = tal(ctx, struct jsonrpc_notification); + n->method = tal_strdup(n, method); + n->stream = new_json_stream(n, NULL); + json_object_start(n->stream, NULL); + json_add_string(n->stream, "jsonrpc", "2.0"); + json_add_string(n->stream, "method", method); + json_object_start(n->stream, "params"); + + return n; +} + +void jsonrpc_notification_end(struct jsonrpc_notification *n) +{ + json_object_end(n->stream); /* closes '.params' */ + json_object_end(n->stream); /* closes '.' */ + json_stream_append(n->stream, "\n\n"); +} + /* We add this destructor as a canary to detect cmd failing. */ static void destroy_command_canary(struct command *cmd, bool *failed) { diff --git a/lightningd/jsonrpc.h b/lightningd/jsonrpc.h index 120e5d812..f923a1add 100644 --- a/lightningd/jsonrpc.h +++ b/lightningd/jsonrpc.h @@ -58,6 +58,14 @@ struct json_command { const char *verbose; }; +struct jsonrpc_notification { + /* The topic that this notification is for. Internally this + * will be serialized as "method", hence the different name + * here */ + const char *method; + struct json_stream *stream; +}; + /** * json_stream_success - start streaming a successful json result. * @cmd: the command we're running. @@ -162,5 +170,18 @@ bool jsonrpc_command_add(struct jsonrpc *rpc, struct json_command *command); */ void jsonrpc_command_remove(struct jsonrpc *rpc, const char *method); +/** + * Begin a JSON-RPC notification with the specified topic. + * + * Automatically starts the `params` object, hence only key-value + * based params are supported at the moment. + */ +struct jsonrpc_notification *jsonrpc_notification_start(const tal_t *ctx, const char *topic); + +/** + * Counterpart to jsonrpc_notification_start. + */ +void jsonrpc_notification_end(struct jsonrpc_notification *n); + AUTODATA_TYPE(json_command, struct json_command); #endif /* LIGHTNING_LIGHTNINGD_JSONRPC_H */