core-lightning/plugins/examples/cln-plugin-startup.rs
Christian Decker 8898511cf6 cln-plugin: Defer binding the plugin state until after configuring
We had a bit of a chicken-and-egg problem, where we instantiated the
`state` to be managed by the `Plugin` during the very first step when
creating the `Builder`, but then the state might depend on the
configuration we only get later. This would force developers to add
placeholders in the form of `Option` into the state, when really
they'd never be none after configuring.

This defers the binding until after we get the configuration and
cleans up the semantics:

 - `Builder`: declare options, hooks, etc
 - `ConfiguredPlugin`: we have exchanged the handshake with
   `lightningd`, now we can construct the `state` accordingly
 - `Plugin`: Running instance of the plugin

Changelog-Changed: cln-plugin: Moved the state binding to the plugin until after the configuration step
2022-09-25 15:13:12 +02:00

44 lines
1.3 KiB
Rust

//! This is a test plugin used to verify that we can compile and run
//! plugins using the Rust API against Core Lightning.
#[macro_use]
extern crate serde_json;
use cln_plugin::{options, Builder, Error, Plugin};
use tokio;
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let state = ();
if let Some(plugin) = Builder::new(tokio::io::stdin(), tokio::io::stdout())
.option(options::ConfigOption::new(
"test-option",
options::Value::Integer(42),
"a test-option with default 42",
))
.rpcmethod("testmethod", "This is a test", testmethod)
.subscribe("connect", connect_handler)
.hook("peer_connected", peer_connected_handler)
.start(state)
.await?
{
plugin.join().await
} else {
Ok(())
}
}
async fn testmethod(_p: Plugin<()>, _v: serde_json::Value) -> Result<serde_json::Value, Error> {
Ok(json!("Hello"))
}
async fn connect_handler(_p: Plugin<()>, v: serde_json::Value) -> Result<(), Error> {
log::info!("Got a connect notification: {}", v);
Ok(())
}
async fn peer_connected_handler(
_p: Plugin<()>,
v: serde_json::Value,
) -> Result<serde_json::Value, Error> {
log::info!("Got a connect hook call: {}", v);
Ok(json!({"result": "continue"}))
}