Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add decodeInvoice method (#19) #35

Open
wants to merge 7 commits into
base: rust
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions bindings/una-js/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export class Node {
createInvoice(invoice: CreateInvoiceParams): Promise<CreateInvoiceResult>
getInfo(): Promise<NodeInfo>
payInvoice(invoice: PayInvoiceParams): Promise<PayInvoiceResult>
decodeInvoice(invoice: String): Promise<DecodeInvoiceResult>
}

export type Backend = "LndRest" | "LndGrpc" | "ClnGrpc" | "EclairRest" | "InvalidBackend";
Expand Down Expand Up @@ -37,6 +38,36 @@ export interface CreateInvoiceResult {
payment_request: string;
}

export type FeatureActivationStatus = "Mandatory" | "Optional" | "Unknown";

export interface DecodeInvoiceResult {
amount?: number | null;
amount_msat?: number | null;
creation_date: number;
destination?: string | null;
expiry: number;
features?: InvoiceFeatures | null;
memo?: string | null;
min_final_cltv_expiry: number;
payment_hash: string;
route_hints: RoutingHint[];
}

export interface InvoiceFeatures {
basic_mpp: FeatureActivationStatus;
option_payment_metadata: FeatureActivationStatus;
payment_secret: FeatureActivationStatus;
var_onion_optin: FeatureActivationStatus;
}

export interface RoutingHint {
chan_id: number;
cltv_expiry_delta: number;
fee_base_msat: number;
fee_proportional_millionths: number;
node_id: string;
}

export type Network =
| ("mainnet" | "testnet" | "regtest")
| {
Expand Down
21 changes: 21 additions & 0 deletions bindings/una-js/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,25 @@ impl JsNode {
|&mut env, payreq| Ok(env.to_js_value(&payreq)),
)
}

#[napi(
ts_args_type = "invoice: String",
ts_return_type = "Promise<DecodeInvoiceResult>"
)]
pub fn decode_invoice(&self, env: Env, invoice_str: String) -> Result<JsObject> {
let node = self.0.clone();

env.execute_tokio_future(
async move {
let invoice = node
.lock()
.await
.decode_invoice(invoice_str)
.await
.or_napi_error()?;
Ok(invoice)
},
|&mut env, invoice| Ok(env.to_js_value(&invoice)),
)
}
}
8 changes: 8 additions & 0 deletions bindings/una-js/test.mjs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Node } from "./index.js";
import "ava";

const config = {
lnd: {
Expand Down Expand Up @@ -55,6 +56,13 @@ async function test_node(backend, config) {
})
.then((result) => console.log(result))
.catch((err) => console.log(err.message, err.code));

node
.decodeInvoice(
"lnbcrt100u1p3n9m8asp5ytfumpvwnehfma235xn50vzffxtrestqzk4qn2up2anwkpucu4nqpp5avpr4r37qpltsjhz543cnnndnz6dqnagepkd35z06lk32ahr7rfsdpz2phkcctjypykuan0d93k2grxdaezqcn0vgxqyjw5qcqp29qyysgqnaa0dtkl4tj3kj8p887pepyjqxhwmwgl5f5xc3mqne6apg2lfg0zj04d79827h5c4ned2m45uc0jl4n63t3l6vvs0pkfdudy2gmmmvqp5qreyk"
)
.then((res) => console.log(res))
.catch((err) => console.error(err.message, err.code));
}

// test_node("LndRest", config.lnd.rest);
Expand Down
2 changes: 1 addition & 1 deletion bindings/una-python/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl From<PyError> for PyErr {
}
}
UnaError::Unauthorized => PyPermissionError::new_err(message),
UnaError::NotImplemented => PyNotImplementedError::new_err(message),
UnaError::NotImplemented(message) => PyNotImplementedError::new_err(message),
UnaError::ConnectionError(message) => {
if message.contains("timeout") {
PyTimeoutError::new_err(message)
Expand Down
20 changes: 18 additions & 2 deletions bindings/una-python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use una_core::{
},
node::{Node, NodeMethods},
types::{
Backend, CreateInvoiceParams, CreateInvoiceResult, NodeConfig, NodeInfo, PayInvoiceParams,
PayInvoiceResult,
Backend, CreateInvoiceParams, CreateInvoiceResult, DecodeInvoiceResult, NodeConfig,
NodeInfo, PayInvoiceParams, PayInvoiceResult,
},
};

Expand Down Expand Up @@ -105,6 +105,22 @@ impl PyNode {
Ok(result)
})
}

pub fn decode_invoice<'p>(&self, py: Python<'p>, invoice_str: String) -> PyResult<&'p PyAny> {
let node = self.0.clone();

pyo3_asyncio::tokio::future_into_py(py, async move {
let result = node
.lock()
.await
.decode_invoice(invoice_str)
.await
.or_py_error()?;
let result =
Python::with_gil(|py| pythonize::<DecodeInvoiceResult>(py, &result).or_py_error())?;
Ok(result)
})
}
}

/// A Python module implemented in Rust.
Expand Down
15 changes: 15 additions & 0 deletions bindings/una-python/test_una.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import pytest
pytest_plugins = ('pytest_asyncio',)


@pytest.fixture
def lnd_rest():
config_lnd_rest = dict({
Expand All @@ -15,6 +16,7 @@ def lnd_rest():
lnd_rest = una.Node("LndRest", config_lnd_rest)
yield lnd_rest


@pytest.fixture
def cln_grpc():
config_cln_grpc = dict({
Expand All @@ -27,11 +29,13 @@ def cln_grpc():
cln_grpc = una.Node("ClnGrpc", config_cln_grpc)
yield cln_grpc


@pytest.mark.asyncio
async def test_get_info(lnd_rest, cln_grpc):
await lnd_rest.get_info()
await cln_grpc.get_info()


@pytest.mark.asyncio
async def test_create_invoice(lnd_rest, cln_grpc):
invoice = dict({
Expand All @@ -42,6 +46,7 @@ async def test_create_invoice(lnd_rest, cln_grpc):
await lnd_rest.create_invoice(invoice)
await cln_grpc.create_invoice(invoice)


@pytest.mark.asyncio
async def test_create_invoice_without_amount(lnd_rest, cln_grpc):
invoice = dict({
Expand All @@ -52,3 +57,13 @@ async def test_create_invoice_without_amount(lnd_rest, cln_grpc):
print(res)
res = await cln_grpc.create_invoice(invoice)
print(res)


@pytest.mark.asyncio
async def test_decode_invoice(lnd_rest, cln_grpc):
invoice = "lnbcrt2400u1p3n9jzupp5ydnyhjmsk3lxg93l9myr9qvxvff0hphvf44j59t4y9kmuq43r5hqdq62pshjmt9de6zqar0yp3kzun0dssp56fskehdusx96zn9mepzcxlpcwhyl0e2a2hl5zyqnsx29grp8g9yqmqz9gxqrrsscqp79q2sqqqqqysgq7rwfghezmteyaunm63efau5f2dufmlz4d5j8mkx4yxfa3dhfsnzreaykvc2dh4fqr6zrw40cxffy8r7rz68425f0e5pfv6nqj5s20mgqr94r57"

res = await lnd_rest.decode_invoice(invoice)
print(res)
res = await cln_grpc.decode_invoice(invoice)
print(res)
1 change: 1 addition & 0 deletions core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ tonic = { version = "0.8.0", features = ["tls"] }
prost = "0.11"
cuid = "1.2.0"
http = "0.2.8"
lightning-invoice = "0.18.0"
regex = "1.6.0"
7 changes: 6 additions & 1 deletion core/src/backends/cln/grpc/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint, Identity
use crate::error::Error;
use crate::node::NodeMethods;
use crate::types::{
CreateInvoiceParams, CreateInvoiceResult, NodeInfo, PayInvoiceParams, PayInvoiceResult,
CreateInvoiceParams, CreateInvoiceResult, DecodeInvoiceResult, NodeInfo, PayInvoiceParams,
PayInvoiceResult,
};

use super::config::ClnGrpcConfig;
Expand Down Expand Up @@ -76,4 +77,8 @@ impl NodeMethods for ClnGrpc {

Ok(response.into())
}

async fn decode_invoice(&self, invoice_str: String) -> Result<DecodeInvoiceResult, Error> {
Ok(invoice_str.try_into()?)
}
}
63 changes: 62 additions & 1 deletion core/src/backends/cln/grpc/pb.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
#![allow(clippy::from_over_into)]

use crate::{types::*, utils};
use std::{convert::TryInto, time::UNIX_EPOCH};

use crate::{error::Error, types::*, utils};
use cuid;
use lightning_invoice;

include!(concat!(env!("PROTOBUFS_DIR"), "/cln.rs"));

Expand Down Expand Up @@ -105,3 +108,61 @@ impl Into<PayInvoiceResult> for PayResponse {
}
}
}

impl TryInto<DecodeInvoiceResult> for String {
type Error = Error;

fn try_into(self) -> Result<DecodeInvoiceResult, Error> {
// DecodeInvoice gRPC command is not implemented yet on CLN, so we need to use an external parser instead
let parsed_invoice =
str::parse::<lightning_invoice::Invoice>(self.as_ref()).map_err(|_| {
Error::ConversionError(String::from(
"provided invoice is not a valid bolt11 invoice",
))
})?;

let memo = match parsed_invoice.description() {
lightning_invoice::InvoiceDescription::Direct(direct) => Ok(direct.to_string()),
lightning_invoice::InvoiceDescription::Hash(_hash) => Err(Error::NotImplemented(
String::from("Hash transcription is not supported yet"),
)),
}?;

let invoice = DecodeInvoiceResult {
creation_date: parsed_invoice
.timestamp()
.duration_since(UNIX_EPOCH)
.map_err(|_| {
Error::ConversionError(String::from("could not convert creation_date"))
})?
.as_millis() as i64,
amount: utils::get_amount_sat(None, parsed_invoice.amount_milli_satoshis()),
amount_msat: parsed_invoice.amount_milli_satoshis(),
destination: None,
louneskmt marked this conversation as resolved.
Show resolved Hide resolved
memo,
payment_hash: parsed_invoice.payment_hash().to_string(),
expiry: parsed_invoice.expiry_time().as_millis() as i32,
min_final_cltv_expiry: parsed_invoice.min_final_cltv_expiry() as u32,
features: None,
route_hints: parsed_invoice
.route_hints()
.into_iter()
.map(|route_hint| RoutingHint {
hop_hints: route_hint
.0
.into_iter()
.map(|hop_int| HopHint {
This conversation was marked as resolved.
Show resolved Hide resolved
node_id: hop_int.src_node_id.to_string(),
chan_id: hop_int.short_channel_id,
fee_base_msat: hop_int.fees.base_msat,
fee_proportional_millionths: hop_int.fees.proportional_millionths,
cltv_expiry_delta: hop_int.cltv_expiry_delta as u32,
})
.collect(),
})
.collect(),
};

Ok(invoice)
}
}
20 changes: 17 additions & 3 deletions core/src/backends/eclair/rest/node.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
use crate::error::Error;
use crate::node::NodeMethods;
use crate::types::{
CreateInvoiceParams, CreateInvoiceResult, NodeInfo, PayInvoiceParams, PayInvoiceResult,
CreateInvoiceParams, CreateInvoiceResult, DecodeInvoiceResult, NodeInfo, PayInvoiceParams,
PayInvoiceResult,
};

use super::config::EclairRestConfig;
use super::types::{
ApiError, ChannelState, CreateInvoiceRequest, CreateInvoiceResponse, GetChannelsResponse,
GetInfoResponse, PayInvoiceRequest, PayInvoiceResponse,
ApiError, ChannelState, CreateInvoiceRequest, CreateInvoiceResponse, DecodeInvoiceRequest,
DecodeInvoiceResponse, GetChannelsResponse, GetInfoResponse, PayInvoiceRequest,
PayInvoiceResponse,
};

pub struct EclairRest {
Expand Down Expand Up @@ -119,4 +121,16 @@ impl NodeMethods for EclairRest {

Ok(data.try_into()?)
}

async fn decode_invoice(&self, invoice: String) -> Result<DecodeInvoiceResult, Error> {
let url = format!("{}/parseinvoice", self.config.url);

let request: DecodeInvoiceRequest = invoice.into();
let mut response = self.client.post(&url).form(&request).send().await?;

response = Self::on_response(response).await?;
let data: DecodeInvoiceResponse = response.json().await?;

data.try_into()
}
}
Loading