diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 1a70ea03f..9a0bf1356 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -25,3 +25,5 @@ jobs:
- name: Check formatting
if: matrix.check-fmt
run: rustup component add rustfmt && cargo fmt --all -- --check
+ - name: Test on Rust ${{ matrix.toolchain }}
+ run: cargo test
diff --git a/.gitignore b/.gitignore
index 088ba6ba7..2acdc0ab4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,7 @@ Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk
+
+*.dylib
+
+ldk_node.kt
diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 000000000..26d33521a
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml
diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml
new file mode 100644
index 000000000..1d9864d6f
--- /dev/null
+++ b/.idea/codeStyles/Project.xml
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml
new file mode 100644
index 000000000..a55e7a179
--- /dev/null
+++ b/.idea/codeStyles/codeStyleConfig.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/ldk-node.iml b/.idea/ldk-node.iml
new file mode 100644
index 000000000..9b4cf845b
--- /dev/null
+++ b/.idea/ldk-node.iml
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 000000000..5a0adcddb
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 000000000..830674470
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Cargo.toml b/Cargo.toml
index d996a65ec..1ca122c18 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,30 +1,66 @@
[package]
-name = "ldk-lite"
+name = "ldk-node"
version = "0.1.0"
authors = ["Elias Rohrer "]
license = "MIT OR Apache-2.0"
edition = "2018"
+description = "A ready-to-go node implementation based on LDK."
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+[lib]
+crate-type = ["staticlib", "cdylib"]
+name = "ldk_node"
+
[dependencies]
-lightning = { version = "0.0.110", features = ["max_level_trace", "std"] }
-lightning-invoice = { version = "0.18" }
-lightning-net-tokio = { version = "0.0.110" }
-lightning-persister = { version = "0.0.110" }
-lightning-background-processor = { version = "0.0.110" }
-lightning-rapid-gossip-sync = { version = "0.0.110" }
+#lightning = { version = "0.0.112", features = ["max_level_trace", "std"] }
+#lightning-invoice = { version = "0.20" }
+#lightning-net-tokio = { version = "0.0.112" }
+#lightning-persister = { version = "0.0.112" }
+#lightning-background-processor = { version = "0.0.112" }
+#lightning-rapid-gossip-sync = { version = "0.0.112" }
+
+#lightning = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main", features = ["max_level_trace", "std"] }
+#lightning-invoice = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
+#lightning-net-tokio = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
+#lightning-persister = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
+#lightning-background-processor = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
+#lightning-rapid-gossip-sync = { git = "https://github.com/lightningdevkit/rust-lightning", branch="main" }
+
+lightning = { git = "https://github.com/tnull/rust-lightning", branch="2022-11-add-transaction-sync-crate", features = ["max_level_trace", "std"] }
+lightning-invoice = { git = "https://github.com/tnull/rust-lightning", branch="2022-11-add-transaction-sync-crate" }
+lightning-net-tokio = { git = "https://github.com/tnull/rust-lightning", branch="2022-11-add-transaction-sync-crate" }
+lightning-persister = { git = "https://github.com/tnull/rust-lightning", branch="2022-11-add-transaction-sync-crate" }
+lightning-background-processor = { git = "https://github.com/tnull/rust-lightning", branch="2022-11-add-transaction-sync-crate" }
+lightning-rapid-gossip-sync = { git = "https://github.com/tnull/rust-lightning", branch="2022-11-add-transaction-sync-crate" }
+lightning-transaction-sync = { git = "https://github.com/tnull/rust-lightning", branch="2022-11-add-transaction-sync-crate", features = ["esplora-async"] }
-#bdk = "0.20.0"
-bdk = { git = "https://github.com/tnull/bdk", branch="feat/use-external-esplora-client", features = ["use-esplora-ureq", "key-value-db"]}
-bitcoin = "0.28.1"
+#lightning = { path = "../rust-lightning/lightning", features = ["max_level_trace", "std"] }
+#lightning-invoice = { path = "../rust-lightning/lightning-invoice" }
+#lightning-net-tokio = { path = "../rust-lightning/lightning-net-tokio" }
+#lightning-persister = { path = "../rust-lightning/lightning-persister" }
+#lightning-background-processor = { path = "../rust-lightning/lightning-background-processor" }
+#lightning-rapid-gossip-sync = { path = "../rust-lightning/lightning-rapid-gossip-sync" }
+#lightning-transaction-sync = { path = "../rust-lightning/lightning-transaction-sync", features = ["esplora-async"] }
+
+bdk = { version = "0.26.0", default-features = false, features = ["async-interface", "use-esplora-async", "key-value-db"]}
+bitcoin = "0.29.2"
rand = "0.8.5"
chrono = "0.4"
futures = "0.3"
serde_json = { version = "1.0" }
-tokio = { version = "1", features = [ "io-util", "macros", "rt", "rt-multi-thread", "sync", "net", "time" ] }
+tokio = { version = "1", features = [ "full" ] }
+uniffi = { version = "0.21.0", features = ["builtin-bindgen"] }
+uniffi_macros = { version = "0.21.0", features = ["builtin-bindgen"] }
+
+[dev-dependencies]
+electrsd = { version = "0.22.0", features = ["legacy", "esplora_a33e97e1", "bitcoind_23_0"] }
+electrum-client = "0.12.0"
+once_cell = "1.16.0"
+[build-dependencies]
+uniffi_build = "0.21.0"
[profile.release]
panic = "abort"
diff --git a/README.md b/README.md
index 70026985e..dd5914b46 100644
--- a/README.md
+++ b/README.md
@@ -1,2 +1,31 @@
# ldk-lite
A Simplified API for LDK.
+
+## Build and publish to local Maven repository
+```shell
+source uniffi_bindgen_generate_kotlin.sh
+cd ldk-node-jvm
+./gradlew publishToMavenLocal
+```
+
+## How to Use
+To use the Kotlin language bindings for [`ldk-node`] in your JVM project, add the following to your gradle dependencies:
+```kotlin
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ implementation("org.ldk:ldk-node:0.0.1")
+}
+```
+
+You may then import and use the `org.ldk_node` library in your Kotlin code. For example:
+```kotlin
+import uniffi.ldk_node.Builder
+import uniffi.ldk_node.Node
+
+fun main() {
+ val node: Node = Builder().build()
+}
+```
diff --git a/build.rs b/build.rs
new file mode 100644
index 000000000..2bd473cd6
--- /dev/null
+++ b/build.rs
@@ -0,0 +1,3 @@
+fn main() {
+ uniffi_build::generate_scaffolding("uniffi/ldk_node.udl").unwrap();
+}
diff --git a/ldk-node-jvm/.gitattributes b/ldk-node-jvm/.gitattributes
new file mode 100644
index 000000000..00a51aff5
--- /dev/null
+++ b/ldk-node-jvm/.gitattributes
@@ -0,0 +1,6 @@
+#
+# https://help.github.com/articles/dealing-with-line-endings/
+#
+# These are explicitly windows files and should use crlf
+*.bat text eol=crlf
+
diff --git a/ldk-node-jvm/.gitignore b/ldk-node-jvm/.gitignore
new file mode 100644
index 000000000..67c4583a2
--- /dev/null
+++ b/ldk-node-jvm/.gitignore
@@ -0,0 +1,7 @@
+# Ignore Gradle project-specific cache directory
+.gradle
+
+# Ignore Gradle build output directory
+build
+
+.idea/
diff --git a/ldk-node-jvm/gradle.properties b/ldk-node-jvm/gradle.properties
new file mode 100644
index 000000000..125e7284f
--- /dev/null
+++ b/ldk-node-jvm/gradle.properties
@@ -0,0 +1 @@
+libraryVersion=0.0.2
diff --git a/ldk-node-jvm/gradle/wrapper/gradle-wrapper.jar b/ldk-node-jvm/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 000000000..41d9927a4
Binary files /dev/null and b/ldk-node-jvm/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/ldk-node-jvm/gradle/wrapper/gradle-wrapper.properties b/ldk-node-jvm/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 000000000..00e33edef
--- /dev/null
+++ b/ldk-node-jvm/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.1-bin.zip
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/ldk-node-jvm/gradlew b/ldk-node-jvm/gradlew
new file mode 100755
index 000000000..1b6c78733
--- /dev/null
+++ b/ldk-node-jvm/gradlew
@@ -0,0 +1,234 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+APP_NAME="Gradle"
+APP_BASE_NAME=${0##*/}
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+# Collect all arguments for the java command;
+# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+# shell script including quotes and variable substitutions, so put them in
+# double quotes to make sure that they get re-expanded; and
+# * put everything else in single quotes, so that it's not re-expanded.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/ldk-node-jvm/gradlew.bat b/ldk-node-jvm/gradlew.bat
new file mode 100644
index 000000000..107acd32c
--- /dev/null
+++ b/ldk-node-jvm/gradlew.bat
@@ -0,0 +1,89 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+
+@if "%DEBUG%" == "" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%" == "" set DIRNAME=.
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if "%ERRORLEVEL%" == "0" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo.
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
+echo.
+echo Please set the JAVA_HOME variable in your environment to match the
+echo location of your Java installation.
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if "%ERRORLEVEL%"=="0" goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
+exit /b 1
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/ldk-node-jvm/lib/build.gradle.kts b/ldk-node-jvm/lib/build.gradle.kts
new file mode 100644
index 000000000..2903e0367
--- /dev/null
+++ b/ldk-node-jvm/lib/build.gradle.kts
@@ -0,0 +1,100 @@
+import org.gradle.api.tasks.testing.logging.TestExceptionFormat.*
+import org.gradle.api.tasks.testing.logging.TestLogEvent.*
+
+// library version is defined in gradle.properties
+val libraryVersion: String by project
+
+plugins {
+ id("org.jetbrains.kotlin.jvm") version "1.5.31"
+ id("java-library")
+ id("maven-publish")
+}
+
+repositories {
+ mavenCentral()
+}
+
+java {
+ sourceCompatibility = JavaVersion.VERSION_1_8
+ targetCompatibility = JavaVersion.VERSION_1_8
+ withSourcesJar()
+ withJavadocJar()
+}
+
+tasks.withType {
+ useJUnitPlatform()
+
+ testLogging {
+ events(PASSED, SKIPPED, FAILED, STANDARD_OUT, STANDARD_ERROR)
+ exceptionFormat = FULL
+ showExceptions = true
+ showCauses = true
+ showStackTraces = true
+ }
+}
+
+dependencies {
+ // Align versions of all Kotlin components
+ implementation(platform("org.jetbrains.kotlin:kotlin-bom"))
+
+ // Use the Kotlin JDK 8 standard library.
+ implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
+
+ implementation("net.java.dev.jna:jna:5.8.0")
+}
+
+afterEvaluate {
+ publishing {
+ publications {
+ create("maven") {
+ groupId = "org.ldk"
+ artifactId = "ldk-node"
+ version = libraryVersion
+
+ from(components["java"])
+ pom {
+ name.set("ldk-node")
+ description.set("Lightning Dev Kit Node language bindings for Kotlin.")
+ url.set("https://lightningdevkit.org")
+ licenses {
+ license {
+ name.set("APACHE 2.0")
+ url.set("https://github.com/bitcoindevkit/bdk/blob/master/LICENSE-APACHE")
+ }
+ license {
+ name.set("MIT")
+ url.set("https://github.com/bitcoindevkit/bdk/blob/master/LICENSE-MIT")
+ }
+ }
+ developers {
+ developer {
+ id.set("")
+ name.set("")
+ email.set("")
+ }
+ developer {
+ id.set("")
+ name.set("")
+ email.set("")
+ }
+ }
+ scm {
+ connection.set("scm:git:github.com/lightningdevkit/ldk-node.git")
+ developerConnection.set("scm:git:ssh://github.com/lightningdevkit/ldk-node.git")
+ url.set("https://github.com/lightningdevkit/ldk-node/tree/master")
+ }
+ }
+ }
+ }
+ }
+}
+
+testing {
+ suites {
+ // Configure the built-in test suite
+ val test by getting(JvmTestSuite::class) {
+ // Use Kotlin Test test framework
+ useKotlinTest()
+ }
+ }
+}
diff --git a/ldk-node-jvm/lib/src/test/kotlin/ldk/node/LibraryTest.kt b/ldk-node-jvm/lib/src/test/kotlin/ldk/node/LibraryTest.kt
new file mode 100644
index 000000000..3914cb939
--- /dev/null
+++ b/ldk-node-jvm/lib/src/test/kotlin/ldk/node/LibraryTest.kt
@@ -0,0 +1,14 @@
+/*
+ * This Kotlin source file was generated by the Gradle 'init' task.
+ */
+package ldk.node
+
+import kotlin.test.Test
+import kotlin.test.assertTrue
+
+class LibraryTest {
+ @Test fun someLibraryMethodReturnsTrue() {
+ val classUnderTest = Library()
+ assertTrue(classUnderTest.someLibraryMethod(), "someLibraryMethod should return 'true'")
+ }
+}
diff --git a/ldk-node-jvm/settings.gradle.kts b/ldk-node-jvm/settings.gradle.kts
new file mode 100644
index 000000000..75e57139a
--- /dev/null
+++ b/ldk-node-jvm/settings.gradle.kts
@@ -0,0 +1,2 @@
+rootProject.name = "ldk-node-jvm"
+include("lib")
diff --git a/src/error.rs b/src/error.rs
index e3b34613a..4f6ddd06f 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -1,130 +1,89 @@
-use bdk::blockchain::esplora;
-use lightning::ln::msgs;
-use lightning::util::errors;
-use lightning_invoice::payment;
use std::fmt;
-use std::io;
-use std::time;
#[derive(Debug)]
/// An error that possibly needs to be handled by the user.
-pub enum LdkLiteError {
- /// Returned when trying to start LdkLite while it is already running.
+pub enum Error {
+ /// Returned when trying to start [`crate::Node`] while it is already running.
AlreadyRunning,
- /// Returned when trying to stop LdkLite while it is not running.
+ /// Returned when trying to stop [`crate::Node`] while it is not running.
NotRunning,
/// The funding transaction could not be created.
FundingTxCreationFailed,
/// A network connection has been closed.
ConnectionFailed,
+ /// The given address is invalid.
+ AddressInvalid,
+ /// The given public key is invalid.
+ PublicKeyInvalid,
+ /// The given payment hash is invalid.
+ PaymentHashInvalid,
/// Payment of the given invoice has already been intiated.
NonUniquePaymentHash,
+ /// The given invoice is invalid.
+ InvoiceInvalid,
+ /// Invoice creation failed.
+ InvoiceCreationFailed,
+ /// The given channel ID is invalid.
+ ChannelIdInvalid,
+ /// No route for the given target could be found.
+ RoutingFailed,
/// A given peer info could not be parsed.
- PeerInfoParse(&'static str),
- /// A wrapped LDK `APIError`
- LdkApi(errors::APIError),
- /// A wrapped LDK `DecodeError`
- LdkDecode(msgs::DecodeError),
- /// A wrapped LDK `PaymentError`
- LdkPayment(payment::PaymentError),
- /// A wrapped LDK `SignOrCreationError`
- LdkInvoiceCreation(lightning_invoice::SignOrCreationError),
- /// A wrapped BDK error
- Bdk(bdk::Error),
- /// A wrapped `EsploraError`
- Esplora(esplora::EsploraError),
- /// A wrapped `Bip32` error
- Bip32(bitcoin::util::bip32::Error),
- /// A wrapped `std::io::Error`
- StdIo(io::Error),
- /// A wrapped `SystemTimeError`
- StdTime(time::SystemTimeError),
+ PeerInfoParseFailed,
+ /// A channel could not be opened.
+ ChannelCreationFailed,
+ /// A channel could not be closed.
+ ChannelClosingFailed,
+ /// Persistence failed.
+ PersistenceFailed,
+ /// A wallet operation failed.
+ WalletOperationFailed,
+ /// A siging operation failed.
+ WalletSigningFailed,
+ /// A transaction sync operation failed.
+ TxSyncFailed,
}
-impl fmt::Display for LdkLiteError {
+impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
- LdkLiteError::AlreadyRunning => write!(f, "LDKLite is already running."),
- LdkLiteError::NotRunning => write!(f, "LDKLite is not running."),
- LdkLiteError::FundingTxCreationFailed => {
- write!(f, "the funding transaction could not be created")
- }
- LdkLiteError::ConnectionFailed => write!(f, "network connection closed"),
- LdkLiteError::NonUniquePaymentHash => write!(f, "an invoice must not get payed twice."),
- LdkLiteError::PeerInfoParse(ref e) => {
- write!(f, "given peer info could not be parsed: {}", e)
- }
- LdkLiteError::LdkDecode(ref e) => write!(f, "LDK decode error: {}", e),
- LdkLiteError::LdkApi(ref e) => write!(f, "LDK API error: {:?}", e),
- LdkLiteError::LdkPayment(ref e) => write!(f, "LDK payment error: {:?}", e),
- LdkLiteError::LdkInvoiceCreation(ref e) => {
- write!(f, "LDK invoice sign or creation error: {:?}", e)
- }
- LdkLiteError::Bdk(ref e) => write!(f, "BDK error: {}", e),
- LdkLiteError::Esplora(ref e) => write!(f, "Esplora error: {}", e),
- LdkLiteError::Bip32(ref e) => write!(f, "Bitcoin error: {}", e),
- LdkLiteError::StdIo(ref e) => write!(f, "IO error: {}", e),
- LdkLiteError::StdTime(ref e) => write!(f, "time error: {}", e),
+ Self::AlreadyRunning => write!(f, "Node is already running."),
+ Self::NotRunning => write!(f, "Node is not running."),
+ Self::FundingTxCreationFailed => write!(f, "Funding transaction could not be created."),
+ Self::ConnectionFailed => write!(f, "Network connection closed."),
+ Self::AddressInvalid => write!(f, "The given address is invalid."),
+ Self::PublicKeyInvalid => write!(f, "The given public key is invalid."),
+ Self::PaymentHashInvalid => write!(f, "The given payment hash is invalid."),
+ Self::NonUniquePaymentHash => write!(f, "An invoice must not get payed twice."),
+ Self::InvoiceInvalid => write!(f, "The given invoice is invalid."),
+ Self::InvoiceCreationFailed => write!(f, "Failed to create invoice."),
+ Self::ChannelIdInvalid => write!(f, "The given channel ID is invalid."),
+ Self::RoutingFailed => write!(f, "Failed to find route."),
+ Self::PeerInfoParseFailed => write!(f, "Failed to parse the given peer information."),
+ Self::ChannelCreationFailed => write!(f, "Failed to create channel."),
+ Self::ChannelClosingFailed => write!(f, "Failed to close channel."),
+ Self::PersistenceFailed => write!(f, "Failed to persist data."),
+ Self::WalletOperationFailed => write!(f, "Failed to conduct wallet operation."),
+ Self::WalletSigningFailed => write!(f, "Failed to sign given transaction."),
+ Self::TxSyncFailed => write!(f, "Failed to sync transactions."),
}
}
}
-impl From for LdkLiteError {
- fn from(e: errors::APIError) -> Self {
- Self::LdkApi(e)
- }
-}
+impl std::error::Error for Error {}
-impl From for LdkLiteError {
- fn from(e: msgs::DecodeError) -> Self {
- Self::LdkDecode(e)
- }
-}
-
-impl From for LdkLiteError {
- fn from(e: payment::PaymentError) -> Self {
- Self::LdkPayment(e)
- }
-}
-
-impl From for LdkLiteError {
- fn from(e: lightning_invoice::SignOrCreationError) -> Self {
- Self::LdkInvoiceCreation(e)
- }
-}
-
-impl From for LdkLiteError {
+impl From for Error {
fn from(e: bdk::Error) -> Self {
- Self::Bdk(e)
- }
-}
-
-impl From for LdkLiteError {
- fn from(e: bdk::sled::Error) -> Self {
- Self::Bdk(bdk::Error::Sled(e))
- }
-}
-
-impl From for LdkLiteError {
- fn from(e: bitcoin::util::bip32::Error) -> Self {
- Self::Bip32(e)
- }
-}
-
-impl From for LdkLiteError {
- fn from(e: io::Error) -> Self {
- Self::StdIo(e)
- }
-}
-
-impl From for LdkLiteError {
- fn from(e: time::SystemTimeError) -> Self {
- Self::StdTime(e)
+ match e {
+ bdk::Error::Signer(_) => Self::WalletSigningFailed,
+ _ => Self::WalletOperationFailed,
+ }
}
}
-impl From for LdkLiteError {
- fn from(e: esplora::EsploraError) -> Self {
- Self::Esplora(e)
+impl From for Error {
+ fn from(e: lightning_transaction_sync::TxSyncError) -> Self {
+ match e {
+ _ => Self::TxSyncFailed,
+ }
}
}
diff --git a/src/event.rs b/src/event.rs
new file mode 100644
index 000000000..4bd62e6e5
--- /dev/null
+++ b/src/event.rs
@@ -0,0 +1,632 @@
+use crate::{
+ hex_utils, ChannelId, ChannelManager, Config, Error, KeysManager, NetworkGraph, PaymentInfo,
+ PaymentInfoStorage, PaymentStatus, UserChannelId, Wallet,
+};
+
+use crate::logger::{log_error, log_given_level, log_info, log_internal, Logger};
+
+use lightning::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator};
+use lightning::ln::PaymentHash;
+use lightning::routing::gossip::NodeId;
+use lightning::util::errors::APIError;
+use lightning::util::events::Event as LdkEvent;
+use lightning::util::events::EventHandler as LdkEventHandler;
+use lightning::util::events::PaymentPurpose;
+use lightning::util::persist::KVStorePersister;
+use lightning::util::ser::{Readable, ReadableArgs, Writeable, Writer};
+
+use bitcoin::secp256k1::Secp256k1;
+use rand::{thread_rng, Rng};
+use std::collections::{hash_map, VecDeque};
+use std::ops::Deref;
+use std::sync::{Arc, Condvar, Mutex, RwLock};
+use std::time::Duration;
+
+/// The event queue will be persisted under this key.
+pub(crate) const EVENTS_PERSISTENCE_KEY: &str = "events";
+
+/// An event emitted by [`Node`], which should be handled by the user.
+///
+/// [`Node`]: [`crate::Node`]
+#[derive(Debug, Clone, PartialEq)]
+pub enum Event {
+ /// A sent payment was successful.
+ PaymentSuccessful {
+ /// The hash of the payment.
+ payment_hash: PaymentHash,
+ },
+ /// A sent payment has failed.
+ PaymentFailed {
+ /// The hash of the payment.
+ payment_hash: PaymentHash,
+ },
+ /// A payment has been received.
+ PaymentReceived {
+ /// The hash of the payment.
+ payment_hash: PaymentHash,
+ /// The value, in thousandths of a satoshi, that has been received.
+ amount_msat: u64,
+ },
+ /// A channel is ready to be used.
+ ChannelReady {
+ /// The `channel_id` of the channel.
+ channel_id: ChannelId,
+ /// The `user_channel_id` of the channel.
+ user_channel_id: UserChannelId,
+ },
+ /// A channel has been closed.
+ ChannelClosed {
+ /// The `channel_id` of the channel.
+ channel_id: ChannelId,
+ /// The `user_channel_id` of the channel.
+ user_channel_id: UserChannelId,
+ },
+}
+
+// TODO: Figure out serialization more concretely - see issue #30
+impl Readable for Event {
+ fn read(
+ reader: &mut R,
+ ) -> Result {
+ match Readable::read(reader)? {
+ 0u8 => {
+ let payment_hash: PaymentHash = Readable::read(reader)?;
+ Ok(Self::PaymentSuccessful { payment_hash })
+ }
+ 1u8 => {
+ let payment_hash: PaymentHash = Readable::read(reader)?;
+ Ok(Self::PaymentFailed { payment_hash })
+ }
+ 2u8 => {
+ let payment_hash: PaymentHash = Readable::read(reader)?;
+ let amount_msat: u64 = Readable::read(reader)?;
+ Ok(Self::PaymentReceived { payment_hash, amount_msat })
+ }
+ 3u8 => {
+ let channel_id = ChannelId(Readable::read(reader)?);
+ let user_channel_id = UserChannelId(Readable::read(reader)?);
+ Ok(Self::ChannelReady { channel_id, user_channel_id })
+ }
+ 4u8 => {
+ let channel_id = ChannelId(Readable::read(reader)?);
+ let user_channel_id = UserChannelId(Readable::read(reader)?);
+ Ok(Self::ChannelClosed { channel_id, user_channel_id })
+ }
+ _ => Err(lightning::ln::msgs::DecodeError::InvalidValue),
+ }
+ }
+}
+
+impl Writeable for Event {
+ fn write(&self, writer: &mut W) -> Result<(), lightning::io::Error> {
+ match self {
+ Self::PaymentSuccessful { payment_hash } => {
+ 0u8.write(writer)?;
+ payment_hash.write(writer)?;
+ Ok(())
+ }
+ Self::PaymentFailed { payment_hash } => {
+ 1u8.write(writer)?;
+ payment_hash.write(writer)?;
+ Ok(())
+ }
+ Self::PaymentReceived { payment_hash, amount_msat } => {
+ 2u8.write(writer)?;
+ payment_hash.write(writer)?;
+ amount_msat.write(writer)?;
+ Ok(())
+ }
+ Self::ChannelReady { channel_id, user_channel_id } => {
+ 3u8.write(writer)?;
+ channel_id.0.write(writer)?;
+ user_channel_id.0.write(writer)?;
+ Ok(())
+ }
+ Self::ChannelClosed { channel_id, user_channel_id } => {
+ 4u8.write(writer)?;
+ channel_id.0.write(writer)?;
+ user_channel_id.0.write(writer)?;
+ Ok(())
+ }
+ }
+ }
+}
+
+pub(crate) struct EventQueue
+where
+ K::Target: KVStorePersister,
+{
+ queue: Mutex>,
+ notifier: Condvar,
+ persister: K,
+}
+
+impl EventQueue
+where
+ K::Target: KVStorePersister,
+{
+ pub(crate) fn new(persister: K) -> Self {
+ let queue: Mutex> = Mutex::new(VecDeque::new());
+ let notifier = Condvar::new();
+ Self { queue, notifier, persister }
+ }
+
+ pub(crate) fn add_event(&self, event: Event) -> Result<(), Error> {
+ {
+ let mut locked_queue = self.queue.lock().unwrap();
+ locked_queue.push_back(event);
+ self.persist_queue(&*locked_queue)?;
+ }
+
+ self.notifier.notify_one();
+ Ok(())
+ }
+
+ pub(crate) fn next_event(&self) -> Event {
+ let locked_queue =
+ self.notifier.wait_while(self.queue.lock().unwrap(), |queue| queue.is_empty()).unwrap();
+ locked_queue.front().unwrap().clone()
+ }
+
+ pub(crate) fn event_handled(&self) -> Result<(), Error> {
+ {
+ let mut locked_queue = self.queue.lock().unwrap();
+ locked_queue.pop_front();
+ self.persist_queue(&*locked_queue)?;
+ }
+ self.notifier.notify_one();
+ Ok(())
+ }
+
+ fn persist_queue(&self, locked_queue: &VecDeque) -> Result<(), Error> {
+ self.persister
+ .persist(EVENTS_PERSISTENCE_KEY, &EventQueueSerWrapper(locked_queue))
+ .map_err(|_| Error::PersistenceFailed)?;
+ Ok(())
+ }
+}
+
+impl ReadableArgs for EventQueue
+where
+ K::Target: KVStorePersister,
+{
+ #[inline]
+ fn read(
+ reader: &mut R, persister: K,
+ ) -> Result {
+ let read_queue: EventQueueDeserWrapper = Readable::read(reader)?;
+ let queue: Mutex> = Mutex::new(read_queue.0);
+ let notifier = Condvar::new();
+ Ok(Self { queue, notifier, persister })
+ }
+}
+
+struct EventQueueDeserWrapper(VecDeque);
+
+impl Readable for EventQueueDeserWrapper {
+ fn read(
+ reader: &mut R,
+ ) -> Result {
+ let len: u16 = Readable::read(reader)?;
+ let mut queue = VecDeque::with_capacity(len as usize);
+ for _ in 0..len {
+ queue.push_back(Readable::read(reader)?);
+ }
+ Ok(Self(queue))
+ }
+}
+
+struct EventQueueSerWrapper<'a>(&'a VecDeque);
+
+impl Writeable for EventQueueSerWrapper<'_> {
+ fn write(&self, writer: &mut W) -> Result<(), lightning::io::Error> {
+ (self.0.len() as u16).write(writer)?;
+ for e in self.0.iter() {
+ e.write(writer)?;
+ }
+ Ok(())
+ }
+}
+
+pub(crate) struct EventHandler
+where
+ K::Target: KVStorePersister,
+ L::Target: Logger,
+{
+ wallet: Arc>,
+ event_queue: Arc>,
+ channel_manager: Arc,
+ network_graph: Arc,
+ keys_manager: Arc,
+ inbound_payments: Arc,
+ outbound_payments: Arc,
+ tokio_runtime: RwLock