lightning

package module
v1.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 14, 2023 License: MIT Imports: 25 Imported by: 16

README

Useful and fast interface for lightningd. All methods return gjson.Result, which is a good thing and very fast. Try the GJSON playground to learn.

Since RPC calls are just relayed and wrapped, you can use lightningd-gjson-rpc to call custom RPC methods if your node has a plugin enabled on it.

godoc.org

This is a simple and resistant client. It is made to survive against faulty lightning node interruptions. It can also talk to spark/sparko HTTP-RPC using the same API, so you can run your app and your node on different machines.

Usage

package main

import (
  "github.com/fiatjaf/lightningd-gjson-rpc"
  "github.com/tidwall/gjson"
)

var ln *lightning.Client

func main () {
    lastinvoiceindex := getFromSomewhereOrStartAtZero()

    ln = &lightning.Client{
        Path:             "/home/whatever/.lightning/lightning-rpc",
        LastInvoiceIndex: lastinvoiceindex, // only needed if you're going to listen for invoices
        PaymentHandler:   handleInvoicePaid, // only needed if you're going to listen for invoices
        CallTimeout: 10 * time.Second, // optional, defaults to 5 seconds
    }
    ln.ListenForInvoices() // optional

    nodeinfo, err := ln.Call("getinfo")
    if err != nil {
        log.Fatal("getinfo error: " + err.Error())
    }

    log.Print(nodeinfo.Get("alias").String())
}

// this is called with the result of `waitanyinvoice`
func handlePaymentReceived(inv gjson.Result) {
    index := inv.Get("pay_index").Int()
    saveSomewhere(index)

    hash := inv.Get("payment_hash").String()
    log.Print("one of our invoices was paid: " + hash)
}

Passing parameters

There are three modes of passing parameters, you can call either:

// 1. `Call` with a list of parameters, in the order defined by each command;
ln.Call("invoice", 1000000, "my-label", "my description", 3600)

// 2. `Call` with a single `map[string]interface{}` with all parameters properly named; or
ln.Call("invoice", map[string]interface{
    "msatoshi": "1000000,
    "label": "my-label",
    "description": "my description",
    "preimage": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"
})

// 3. `CallNamed` with a list of keys and values passed in the proper order.
ln.CallNamed("invoice",
    "msatoshi", "1000000,
    "label", "my-label",
    "description", "my description",
    "preimage", "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
    "expiry", 3600,
)

Special methods

Besides providing full access to the c-lightning RPC interface with .Call methods, we also have ListenForInvoices, PayAndWaitUntilResolution and GetPrivateKey to make your life better.

It's good to say also that since we don't have hardcoded methods here you can call custom RPC methods with this library.

Plugins

If you want to write a plugin, we provide helpers to make that easy. Take a look at https://github.com/fiatjaf/sparko or https://github.com/fiatjaf/lightningd-webhook for examples.

Documentation

Index

Constants

View Source
const DESCRIPTION_HASH_DESCRIPTION_PREFIX = "with description_hash: "

Variables

View Source
var DefaultTimeout = time.Second * 5
View Source
var InvoiceListeningTimeout = time.Minute * 150

Functions

This section is empty.

Types

type Channel added in v1.0.0

type Channel struct {
	Source              string `json:"source"`
	Destination         string `json:"destination"`
	ShortChannelID      string `json:"short_channel_id"`
	BaseFeeMillisatoshi int64  `json:"base_fee_millisatoshi"`
	FeePerMillionth     int64  `json:"fee_per_millionth"`
	Delay               int64  `json:"delay"`
	Direction           int    `json:"direction"`
	HtlcMinimumMsat     int64  `json:"htlc_minimum_msat"`
	HtlcMaximumMsat     int64  `json:"htlc_maximum_msat"`
	// contains filtered or unexported fields
}

func (*Channel) Fee added in v1.0.0

func (c *Channel) Fee(msatoshi, riskfactor int64, fuzzpercent float64) int64

type Client

type Client struct {
	PaymentHandler   func(gjson.Result)
	LastInvoiceIndex int
	CallTimeout      time.Duration

	// lightning-rpc socket
	Path         string
	LightningDir string

	// spark/sparko server
	SparkURL              string
	SparkToken            string
	DontCheckCertificates bool
}

func (*Client) Call

func (ln *Client) Call(method string, params ...interface{}) (gjson.Result, error)

func (*Client) CallMessage

func (ln *Client) CallMessage(timeout time.Duration, message JSONRPCMessage) (gjson.Result, error)

func (*Client) CallMessageRaw

func (ln *Client) CallMessageRaw(timeout time.Duration, message JSONRPCMessage) ([]byte, error)

func (*Client) CallNamed

func (ln *Client) CallNamed(method string, params ...interface{}) (gjson.Result, error)

func (*Client) CallNamedWithCustomTimeout

func (ln *Client) CallNamedWithCustomTimeout(
	timeout time.Duration,
	method string,
	params ...interface{},
) (res gjson.Result, err error)

func (*Client) CallWithCustomTimeout

func (ln *Client) CallWithCustomTimeout(
	timeout time.Duration,
	method string,
	params ...interface{},
) (gjson.Result, error)

func (*Client) GetCustomBytes added in v1.0.0

func (ln *Client) GetCustomBytes(
	index byte,
	label string,
) (b []byte, err error)

func (*Client) GetCustomKey added in v1.0.0

func (ln *Client) GetCustomKey(
	index byte,
	label string,
) (sk *btcec.PrivateKey, err error)

GetCustomKey reads the hsm_secret file in the same directory as the lightning-rpc socket (given by Client.Path) and derives the node private key from it.

func (*Client) GetPath added in v1.0.0

func (ln *Client) GetPath(
	id string,
	msatoshi int64,
	fromid string,
	exclude []string,
	maxhops int,
	maxchannelfeepercent float64,
) (path []*Channel, err error)

func (*Client) GetPrivateKey added in v1.0.0

func (ln *Client) GetPrivateKey() (sk *btcec.PrivateKey, err error)

GetPrivateKey gets the custom key with the parameters that return the node's master key (0 and "nodeid")

func (*Client) GetRoute added in v1.0.0

func (ln *Client) GetRoute(
	id string,
	msatoshi int64,
	riskfactor int64,
	cltv int64,
	fromid string,
	fuzzpercent float64,
	exclude []string,
	maxhops int,
	maxchannelfeepercent float64,
) (route []RouteHop, err error)

func (*Client) InvoiceWithDescriptionHash added in v1.0.0

func (ln *Client) InvoiceWithDescriptionHash(
	label string,
	msatoshi int64,
	descriptionHash []byte,
	ppreimage *[]byte,
	pexpiry *time.Duration,
) (bolt11 string, err error)

func (*Client) InvoiceWithShadowRoute added in v1.1.0

func (ln *Client) InvoiceWithShadowRoute(
	msatoshi int64,
	descriptionOrHash interface{},
	ppreimage *[]byte,
	pprivateKey **btcec.PrivateKey,
	pexpiry *time.Duration,
	baseFee uint32,
	ppmFee uint32,
	cltvExpiryDelta uint16,
	channelId uint64,
) (bolt11 string, paymentHash string, err error)

func (*Client) ListenForInvoices

func (ln *Client) ListenForInvoices()

ListenForInvoices starts a goroutine that will repeatedly call waitanyinvoice. Each payment received will be fed into the client.PaymentHandler function. You can change that function in the meantime. Or you can set it to nil if you want to stop listening for invoices.

func (*Client) TranslateInvoiceWithDescriptionHash added in v1.4.1

func (ln *Client) TranslateInvoiceWithDescriptionHash(bolt11 string) (string, error)

type ErrorCommand

type ErrorCommand struct {
	Message string      `json:"msg"`
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
}

func (ErrorCommand) Error

func (l ErrorCommand) Error() string

type ErrorConnect

type ErrorConnect struct {
	Path    string `json:"path"`
	Message string `json:"message"`
}

func (ErrorConnect) Error

func (c ErrorConnect) Error() string

type ErrorConnectionBroken

type ErrorConnectionBroken struct{}

func (ErrorConnectionBroken) Error

func (c ErrorConnectionBroken) Error() string

type ErrorJSONDecode

type ErrorJSONDecode struct {
	Message string `json:"message"`
}

func (ErrorJSONDecode) Error

func (j ErrorJSONDecode) Error() string

type ErrorNetwork added in v1.0.0

type ErrorNetwork struct {
	URL     string `json:"url"`
	Message string `json:"message"`
}

type ErrorTimeout

type ErrorTimeout struct {
	Seconds int `json:"seconds"`
}

func (ErrorTimeout) Error

func (t ErrorTimeout) Error() string

type Graph added in v1.0.0

type Graph struct {
	// contains filtered or unexported fields
}

func (*Graph) SearchDualBFS added in v1.0.0

func (g *Graph) SearchDualBFS(start string, end string) (path []*Channel)

func (*Graph) Sync added in v1.0.0

func (g *Graph) Sync() error

type JSONRPCError

type JSONRPCError struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data"`
}

type JSONRPCMessage

type JSONRPCMessage struct {
	Version string      `json:"jsonrpc"`
	Id      interface{} `json:"id"`
	Method  string      `json:"method"`
	Params  interface{} `json:"params"`
}

type JSONRPCResponse

type JSONRPCResponse struct {
	Version string          `json:"jsonrpc"`
	Id      interface{}     `json:"id"`
	Result  json.RawMessage `json:"result,omitempty"`
	Error   *JSONRPCError   `json:"error,omitempty"`
}

type RouteHop added in v1.0.0

type RouteHop struct {
	Id        string `json:"id"`
	Channel   string `json:"channel"`
	Direction int    `json:"direction"`
	Msatoshi  int64  `json:"msatoshi"`
	Delay     int64  `json:"delay"`
	// contains filtered or unexported fields
}

func PathToRoute added in v1.0.0

func PathToRoute(
	path []*Channel,
	msatoshi int64,
	cltv int64,
	riskfactor int64,
	fuzzpercent float64,
) (route []RouteHop)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL