lightning_go

package module
v0.15.2 Latest Latest
Warning

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

Go to latest
Published: Oct 7, 2022 License: MIT Imports: 33 Imported by: 5

README

lightning-go

License

This golang library is used by Chainpoint Core to connect with a Lightning Network Daemon over grpc. By default Lightning, Wallet, WalletUnlocker, and Invoice clients are available. A number of convenience methods for working with Lightning Service Authentication Tokens and interacting with the Bitcoin blockchain are also provided. By default this library is intended to work with Tierion Inc's fork of lnd, but other than exposing a block retrieval method, there is little difference from the original repository.

Install

This package requires Go modules.

go get github.com/chainpoint/lightning-go

Usage

A basic example of declaring the library is provided below.

package main

import (
    lightning "github.com/chainpoint/lightning-go"
    "encoding/json"
    "fmt"
    "time"
)

func main() {
    lndClient := lightning.LightningClient{
                        TlsPath:             "/home/ubuntu/.lnd/tls.cert",
                        MacPath:             "/home/ubuntu/.lnd/data/chain/bitcoin/mainnet/admin.macaroon",
                        ServerHostPort:      "127.0.0.1:10009",
                        LndLogLevel:         "error",
                        MinConfs:            3,
                        Testnet:             "mainnet",
                        WalletAddress:       "your_wallet_address",
                        WalletPass:          "your_wallet_password",
                        WalletSeed:          "your_wallet_seed",
                        HashPrice:           int64(2), //price to charge for issuing LSAT
                        SessionSecret:       "a mutual secret between lsat servers and clients",
                  }
     lndClient.WaitForConnection(5 * time.Minute)  //Wait until lnd is ready
     lndClient.Unlocker()                          //Unlock wallet 
     info, err := lndClient.GetInfo()              //Make a call to get lnd node info
     if err == nil {
         infoJson, _ := json.Marshal(info)
         fmt.Println(string(infoJson)) 
     }
}

Additionally an example of a server-side LSAT flow, RespondLSAT, is provided in lsat.go

Documentation

Index

Constants

View Source
const (
	// LatestVersion is the latest version used for minting new LSATs.
	LatestVersion = 0

	// SecretSize is the size in bytes of a LSAT's secret, also known as
	// the root key of the macaroon.
	SecretSize = 32

	// TokenIDSize is the size in bytes of an LSAT's ID encoded in its
	// macaroon identifier.
	TokenIDSize = 32
)
View Source
const (
	// PreimageKey is the key used for a payment preimage caveat.
	PreimageKey = "preimage"
)

Variables

View Source
var (
	// ErrInvalidCaveat is an error returned when we attempt to decode a
	// caveat with an invalid format.
	ErrInvalidCaveat = errors.New("caveat must be of the form " +
		"\"condition=value\"")
)
View Source
var (

	// ErrUnknownVersion is an error returned when attempting to decode an
	// LSAT identifier with an unknown version.
	ErrUnknownVersion = errors.New("unknown LSAT version")
)

Functions

func AddFirstPartyCaveats

func AddFirstPartyCaveats(m *macaroon.Macaroon, caveats ...Caveat) error

AddFirstPartyCaveats adds a set of caveats as first-party caveats to a macaroon.

func EncodeCaveat

func EncodeCaveat(c Caveat) string

EncodeCaveat encodes a caveat into its string representation.

func EncodeIdentifier

func EncodeIdentifier(w io.Writer, id *Identifier) error

EncodeIdentifier encodes an LSAT's identifier according to its version.

func GenerateRandomBytes

func GenerateRandomBytes(n int) ([]byte, error)

GenerateRandomBytes returns securely generated random bytes. It will return an error if the system's secure random number generator fails to function correctly, in which case the caller should not continue.

func GetCurrentFuncName

func GetCurrentFuncName(numCallStack int) string

GetCurrentFuncName : get name of function being called

func GetIpFromUri

func GetIpFromUri(uri string) string

GetIpFromUri : parses and IP from a uri as determined by IsLnUri

func HasCaveat

func HasCaveat(m *macaroon.Macaroon, cond string) (string, bool)

HasCaveat checks whether the given macaroon has a caveat with the given condition, and if so, returns its value. If multiple caveats with the same condition exist, then the value of the last one is returned.

func IsLnUri

func IsLnUri(uri string) bool

IsLnUri : determines if a url meets criteria <pub_key>@<ip>:<port>

Types

type Caveat

type Caveat struct {
	// Condition serves as a way to identify a caveat and how to satisfy it.
	Condition string

	// Value is what will be used to satisfy a caveat. This can be as
	// flexible as needed, as long as it can be encoded into a string.
	Value string
}

Caveat is a predicate that can be applied to an LSAT in order to restrict its use in some form. Caveats are evaluated during LSAT verification after the LSAT's signature is verified. The predicate of each caveat must hold true in order to successfully validate an LSAT.

func DecodeCaveat

func DecodeCaveat(s string) (Caveat, error)

DecodeCaveat decodes a caveat from its string representation.

func NewCaveat

func NewCaveat(condition string, value string) Caveat

NewCaveat construct a new caveat with the given condition and value.

func (Caveat) String

func (c Caveat) String() string

String returns a user-friendly view of a caveat.

type Identifier

type Identifier struct {
	// Version is the version of an LSAT. Having a version allows us to
	// introduce new fields to the identifier in a backwards-compatible
	// manner.
	Version uint16

	// PaymentHash is the payment hash linked to an LSAT. Verification of
	// an LSAT depends on a valid payment, which is enforced by ensuring a
	// preimage is provided that hashes to our payment hash.
	PaymentHash lntypes.Hash

	// TokenID is the unique identifier of an LSAT.
	TokenID TokenID
}

Identifier contains the static identifying details of an LSAT. This is intended to be used as the identifier of the macaroon within an LSAT.

func DecodeIdentifier

func DecodeIdentifier(r io.Reader) (*Identifier, error)

DecodeIdentifier decodes an LSAT's identifier according to its version.

type LSAT

type LSAT struct {
	ID       TokenID
	Preimage []byte
	PayHash  []byte
	Invoice  string
	Value    int64
	Macaroon macaroon.Macaroon
}

func FromHeader

func FromHeader(header *http.Header) (LSAT, error)

func (*LSAT) ToChallenge

func (lsat *LSAT) ToChallenge() string

func (*LSAT) ToToken

func (lsat *LSAT) ToToken() string

type LightningClient

type LightningClient struct {
	ServerHostPort string
	TlsPath        string
	MacPath        string
	MinConfs       int64
	TargetConfs    int64
	LndLogLevel    string
	Testnet        bool
	WalletAddress  string
	WalletPass     string
	WalletSeed     []string
	LastFee        int64
	HashPrice      int64
	SessionSecret  string
	NoMacaroons    bool
}

func CreateClient

func CreateClient(serverHostPort string, tlsPath string, macPath string) LightningClient

CreateClient : creates a new basic client struct

func (*LightningClient) AddPeer

func (ln *LightningClient) AddPeer(peer string) error

AddPeer : adds a peer conforming to lnd uri spec to the current node

func (*LightningClient) AnyChannelExists

func (ln *LightningClient) AnyChannelExists(peer string, satVal int64) (bool, error)

AnyChannelExists : determine if any channel, active or pending, exists for this peer with satVal value or greater.

func (*LightningClient) CreateChannel

func (ln *LightningClient) CreateChannel(peer string, satVal int64) (lnrpc.Lightning_OpenChannelClient, error)

CreateChannel : open and fund a channel of a satVal amount to a peer.

func (*LightningClient) CreateConn

func (ln *LightningClient) CreateConn() (*grpc.ClientConn, error)

Create a connection to a lightning node with a tls cert path and a macaroon path. Used by most other methods

func (*LightningClient) GenSeed

func (ln *LightningClient) GenSeed() ([]string, error)

GenSeed : generate a wallet seed. Used for InitWallet

func (*LightningClient) GenerateHodlLSAT

func (ln *LightningClient) GenerateHodlLSAT(ip string) (LSAT, error)

func (*LightningClient) GetChannels

func (ln *LightningClient) GetChannels() (*lnrpc.ListChannelsResponse, error)

GetChannels : retrieve all active and funded channels

func (*LightningClient) GetClient

func (ln *LightningClient) GetClient() (lnrpc.LightningClient, func(), error)

GetClient : Returns default lightning grpc client

func (*LightningClient) GetInfo

func (ln *LightningClient) GetInfo() (*lnrpc.GetInfoResponse, error)

GetInfo : retrieves basic lnd node info

func (*LightningClient) GetInvoiceClient

func (ln *LightningClient) GetInvoiceClient() (invoicesrpc.InvoicesClient, func(), error)

GetInvoiceClient : retrieve invoice grpc client

func (*LightningClient) GetLndFeeEstimate

func (ln *LightningClient) GetLndFeeEstimate() (int64, error)

GetLndFeeEstimate : retrieve fee from lnd node's designated fee estimator

func (*LightningClient) GetPendingChannels

func (ln *LightningClient) GetPendingChannels() (*lnrpc.PendingChannelsResponse, error)

GetPendingChannels : get channels that have not yet had a funding btc tx confirmed

func (*LightningClient) GetTransaction

func (ln *LightningClient) GetTransaction(id []byte) (lnrpc.TransactionDetails, error)

GetTransaction : retrieves a transaction from the current unlocked wallet matching @id

func (*LightningClient) GetWalletBalance

func (ln *LightningClient) GetWalletBalance() (*lnrpc.WalletBalanceResponse, error)

GetWalletBalance : retrieves balance from the current wallet

func (*LightningClient) GetWalletClient

func (ln *LightningClient) GetWalletClient() (walletrpc.WalletKitClient, func(), error)

GetWalletClient : returns wallet grpc client

func (*LightningClient) GetWalletUnlockerClient

func (ln *LightningClient) GetWalletUnlockerClient() (lnrpc.WalletUnlockerClient, func(), error)

GetWalletUnlockerClient : returns wallet unlocker grpc client- non-authenticated session

func (*LightningClient) InitWallet

func (ln *LightningClient) InitWallet() error

InitWallet : initialize wallet with given cipher phrase and passwors

func (*LightningClient) LookupInvoice

func (ln *LightningClient) LookupInvoice(payhash []byte) (lnrpc.Invoice, error)

LookupInvoices : Retrieve an invoice by payment hash. used for LSAT authentication

func (*LightningClient) NewAddress

func (ln *LightningClient) NewAddress() (string, error)

NewAddress : create a new address for a wallet. Returns the wallet address or an error

func (*LightningClient) OurChannelOpenAndFunded

func (ln *LightningClient) OurChannelOpenAndFunded(peer string, satVal int64) (bool, error)

OurChannelOpenAndFunded : determine if the current node has opened a channel of a certain value or greater

func (*LightningClient) PeerExists

func (ln *LightningClient) PeerExists(peer string) (bool, error)

PeerExists : determine if the current lnd node is connected to a particular peer. peer must be an lnd uri.

func (*LightningClient) RemoteChannelOpenAndFunded

func (ln *LightningClient) RemoteChannelOpenAndFunded(peer string, satVal int64) (bool, error)

RemoteChannelOpenAndFunded : determine if a remote peer has opened a channel of a certain value or greater

func (*LightningClient) ReplaceByFee

func (ln *LightningClient) ReplaceByFee(txid string, OPRETURNIndex bool, newfee int) (walletrpc.BumpFeeResponse, error)

ReplaceByFee : retrieve a pending transaction and implement rbf. Not currently functional.

func (*LightningClient) RespondLSAT

func (ln *LightningClient) RespondLSAT(w http.ResponseWriter, r *http.Request) bool

RespondLSAT : Use this in an http handler to issue an LSAT challenge Returns true to signal a required return from an http handler, false to fall through

func (*LightningClient) SendCoins

func (ln *LightningClient) SendCoins(addr string, amt int64, confs int32) (lnrpc.SendCoinsResponse, error)

SendCoins ; send amt of satothis to addr address and wait for confs confirmations

func (*LightningClient) SendOpReturn

func (ln *LightningClient) SendOpReturn(hash []byte) (string, string, error)

SendOpReturn : send an op return as an output from the connected lnd node

func (*LightningClient) SubscribeInvoicesCallback added in v0.0.3

func (ln *LightningClient) SubscribeInvoicesCallback(quit chan struct{}, callback func(inv lnrpc.Invoice)) error

SubscribeInvoicesCallBack : call a callback with a new invoice as a parameter

func (*LightningClient) SubscribeInvoicesChannel added in v0.0.3

func (ln *LightningClient) SubscribeInvoicesChannel(quit chan struct{}, errc chan error, results chan lnrpc.Invoice)

SubscribeInvoicesChannel : send new invoices to a channel

func (*LightningClient) Unlocker

func (ln *LightningClient) Unlocker() error

Unlocker: unlock wallet using wallet unlocker client based on this LightningClient's password

func (*LightningClient) WaitForConnection

func (ln *LightningClient) WaitForConnection(d time.Duration) error

WaitForConnection : Wait for a connection to an lnd node to be ready within d amount of time

func (*LightningClient) WaitForMacaroon

func (ln *LightningClient) WaitForMacaroon(d time.Duration) error

WaitForMacaroon : wait for an lnd node to create a macaroon within d amount of time

func (*LightningClient) WaitForNewAddress

func (ln *LightningClient) WaitForNewAddress(d time.Duration) (string, error)

WaitForNewAddress : wait until a new address call succeeds within d amount of time, or error

func (*LightningClient) WaitForSync added in v0.15.2

func (ln *LightningClient) WaitForSync(d time.Duration) error

WaitForSync : wait until synced

type TokenID

type TokenID [TokenIDSize]byte

TokenID is the type that stores the token identifier of an LSAT token.

func MakeIDFromString

func MakeIDFromString(newID string) (TokenID, error)

MakeIDFromString parses the hex encoded string and parses it into a token ID.

func (*TokenID) String

func (t *TokenID) String() string

String returns the hex encoded representation of the token ID as a string.

Jump to

Keyboard shortcuts

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