2015-12-30 05:31:03 +03:00
package main
import (
2018-02-02 07:52:40 +03:00
"bufio"
2015-12-30 05:58:58 +03:00
"bytes"
2016-07-13 03:47:24 +03:00
"encoding/hex"
2015-12-30 05:31:03 +03:00
"encoding/json"
2018-01-24 05:34:29 +03:00
"errors"
2016-04-25 06:27:19 +03:00
"fmt"
2016-07-08 01:35:06 +03:00
"io"
2017-01-24 07:32:17 +03:00
"io/ioutil"
2017-01-25 05:07:15 +03:00
"math"
2015-12-30 05:58:58 +03:00
"os"
2017-01-24 07:32:17 +03:00
"os/exec"
"strconv"
2016-06-21 22:35:07 +03:00
"strings"
2018-01-24 05:34:29 +03:00
"sync"
2017-12-19 01:04:04 +03:00
"syscall"
2016-12-27 08:52:15 +03:00
2017-01-24 07:32:17 +03:00
"github.com/awalterschulze/gographviz"
2017-01-30 01:56:31 +03:00
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
2016-01-16 21:45:54 +03:00
"github.com/lightningnetwork/lnd/lnrpc"
2017-01-06 00:56:27 +03:00
"github.com/roasbeef/btcd/chaincfg/chainhash"
2017-01-24 07:32:17 +03:00
"github.com/roasbeef/btcutil"
2016-07-26 20:42:35 +03:00
"github.com/urfave/cli"
2017-10-12 12:42:06 +03:00
"golang.org/x/crypto/ssh/terminal"
2015-12-30 05:31:03 +03:00
"golang.org/x/net/context"
2017-11-07 01:34:49 +03:00
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
2015-12-30 05:31:03 +03:00
)
2016-06-21 22:35:07 +03:00
// TODO(roasbeef): cli logic for supporting both positional and unix style
// arguments.
2017-11-23 22:40:14 +03:00
// TODO(roasbeef): expose all fee conf targets
2017-02-23 22:56:47 +03:00
func printJSON ( resp interface { } ) {
2015-12-30 05:58:58 +03:00
b , err := json . Marshal ( resp )
if err != nil {
fatal ( err )
}
var out bytes . Buffer
json . Indent ( & out , b , "" , "\t" )
2017-03-16 22:06:12 +03:00
out . WriteString ( "\n" )
2015-12-30 05:58:58 +03:00
out . WriteTo ( os . Stdout )
}
2017-02-23 22:56:47 +03:00
func printRespJSON ( resp proto . Message ) {
2017-01-30 01:56:31 +03:00
jsonMarshaler := & jsonpb . Marshaler {
EmitDefaults : true ,
Indent : " " ,
}
jsonStr , err := jsonMarshaler . MarshalToString ( resp )
if err != nil {
fmt . Println ( "unable to decode response: " , err )
return
}
fmt . Println ( jsonStr )
}
2017-11-07 01:34:49 +03:00
// actionDecorator is used to add additional information and error handling
// to command actions.
func actionDecorator ( f func ( * cli . Context ) error ) func ( * cli . Context ) error {
return func ( c * cli . Context ) error {
if err := f ( c ) ; err != nil {
// lnd might be active, but not possible to contact
// using RPC if the wallet is encrypted. If we get
// error code Unimplemented, it means that lnd is
// running, but the RPC server is not active yet (only
// WalletUnlocker server active) and most likely this
// is because of an encrypted wallet.
s , ok := status . FromError ( err )
if ok && s . Code ( ) == codes . Unimplemented {
return fmt . Errorf ( "Wallet is encrypted. " +
"Please unlock using 'lncli unlock', " +
"or set password using 'lncli create'" +
" if this is the first time starting " +
"lnd." )
}
return err
}
return nil
}
}
2017-02-24 16:32:33 +03:00
var newAddressCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "newaddress" ,
2018-02-06 02:05:04 +03:00
Usage : "Generates a new address." ,
2017-03-03 01:23:16 +03:00
ArgsUsage : "address-type" ,
2017-11-23 22:40:14 +03:00
Description : `
Generate a wallet new address . Address - types has to be one of :
2018-02-18 02:41:34 +03:00
- p2wkh : Pay to witness key hash
- np2wkh : Pay to nested witness key hash ` ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( newAddress ) ,
2015-12-30 05:31:03 +03:00
}
2016-06-29 23:01:08 +03:00
func newAddress ( ctx * cli . Context ) error {
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2015-12-30 05:31:03 +03:00
2017-03-03 01:23:16 +03:00
stringAddrType := ctx . Args ( ) . First ( )
2016-04-25 06:27:19 +03:00
// Map the string encoded address type, to the concrete typed address
// type enum. An unrecognized address type will result in an error.
var addrType lnrpc . NewAddressRequest_AddressType
switch stringAddrType { // TODO(roasbeef): make them ints on the cli?
case "p2wkh" :
addrType = lnrpc . NewAddressRequest_WITNESS_PUBKEY_HASH
case "np2wkh" :
addrType = lnrpc . NewAddressRequest_NESTED_PUBKEY_HASH
default :
2016-06-29 23:01:08 +03:00
return fmt . Errorf ( "invalid address type %v, support address type " +
2018-02-18 02:41:34 +03:00
"are: p2wkh and np2wkh" , stringAddrType )
2016-04-25 06:27:19 +03:00
}
2015-12-30 05:31:03 +03:00
ctxb := context . Background ( )
2016-04-25 06:27:19 +03:00
addr , err := client . NewAddress ( ctxb , & lnrpc . NewAddressRequest {
Type : addrType ,
} )
2015-12-30 05:31:03 +03:00
if err != nil {
2016-06-29 23:01:08 +03:00
return err
2015-12-30 05:31:03 +03:00
}
2017-02-23 22:56:47 +03:00
printRespJSON ( addr )
2016-06-29 23:01:08 +03:00
return nil
2015-12-30 05:31:03 +03:00
}
2017-02-24 16:32:33 +03:00
var sendCoinsCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "sendcoins" ,
2018-02-06 02:05:04 +03:00
Usage : "Send bitcoin on-chain to an address" ,
2017-03-03 01:23:16 +03:00
ArgsUsage : "addr amt" ,
2017-11-23 22:40:14 +03:00
Description : `
Send amt coins in satoshis to the BASE58 encoded bitcoin address addr .
Fees used when sending the transaction can be specified via the -- conf_target , or
-- sat_per_byte optional flags .
Positional arguments and flags can be used interchangeably but not at the same time !
` ,
2016-06-29 21:29:21 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "addr" ,
2017-03-03 01:23:16 +03:00
Usage : "the BASE58 encoded bitcoin address to send coins to on-chain" ,
2016-06-29 21:29:21 +03:00
} ,
// TODO(roasbeef): switch to BTC on command line? int may not be sufficient
2017-03-03 01:23:16 +03:00
cli . Int64Flag {
2016-06-29 21:29:21 +03:00
Name : "amt" ,
Usage : "the number of bitcoin denominated in satoshis to send" ,
} ,
2017-11-23 22:40:14 +03:00
cli . Int64Flag {
Name : "conf_target" ,
Usage : "(optional) the number of blocks that the " +
"transaction *should* confirm in, will be " +
"used for fee estimation" ,
} ,
cli . Int64Flag {
Name : "sat_per_byte" ,
Usage : "(optional) a manual fee expressed in " +
"sat/byte that should be used when crafting " +
"the transaction" ,
} ,
2016-06-29 21:29:21 +03:00
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( sendCoins ) ,
2016-06-29 21:29:21 +03:00
}
2016-06-29 23:01:08 +03:00
func sendCoins ( ctx * cli . Context ) error {
2017-03-03 01:23:16 +03:00
var (
addr string
amt int64
err error
)
args := ctx . Args ( )
if ctx . NArg ( ) == 0 && ctx . NumFlags ( ) == 0 {
cli . ShowCommandHelp ( ctx , "sendcoins" )
return nil
}
2017-11-23 22:40:14 +03:00
if ctx . IsSet ( "conf_target" ) && ctx . IsSet ( "sat_per_byte" ) {
return fmt . Errorf ( "either conf_target or sat_per_byte should be " +
"set, but not both" )
}
2017-03-03 01:23:16 +03:00
switch {
case ctx . IsSet ( "addr" ) :
addr = ctx . String ( "addr" )
case args . Present ( ) :
addr = args . First ( )
args = args . Tail ( )
default :
return fmt . Errorf ( "Address argument missing" )
}
switch {
case ctx . IsSet ( "amt" ) :
amt = ctx . Int64 ( "amt" )
case args . Present ( ) :
amt , err = strconv . ParseInt ( args . First ( ) , 10 , 64 )
default :
return fmt . Errorf ( "Amount argument missing" )
}
if err != nil {
return fmt . Errorf ( "unable to decode amount: %v" , err )
}
2016-06-29 21:29:21 +03:00
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-06-29 21:29:21 +03:00
req := & lnrpc . SendCoinsRequest {
2017-11-23 22:40:14 +03:00
Addr : addr ,
Amount : amt ,
TargetConf : int32 ( ctx . Int64 ( "conf_target" ) ) ,
SatPerByte : ctx . Int64 ( "sat_per_byte" ) ,
2016-06-29 21:29:21 +03:00
}
txid , err := client . SendCoins ( ctxb , req )
if err != nil {
2016-06-29 23:01:08 +03:00
return err
2016-06-29 21:29:21 +03:00
}
2017-02-23 22:56:47 +03:00
printRespJSON ( txid )
2016-06-29 23:01:08 +03:00
return nil
2016-06-29 21:29:21 +03:00
}
2017-02-24 16:32:33 +03:00
var sendManyCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "sendmany" ,
2018-02-06 02:05:04 +03:00
Usage : "Send bitcoin on-chain to multiple addresses." ,
2017-11-23 22:40:14 +03:00
ArgsUsage : "send-json-string [--conf_target=N] [--sat_per_byte=P]" ,
Description : `
Create and broadcast a transaction paying the specified amount ( s ) to the passed address ( es ) .
The send - json - string ' param decodes addresses and the amount to send
respectively in the following format :
' { "ExampleAddr" : NumCoinsInSatoshis , "SecondAddr" : NumCoins } '
` ,
Flags : [ ] cli . Flag {
cli . Int64Flag {
Name : "conf_target" ,
Usage : "(optional) the number of blocks that the transaction *should* " +
"confirm in, will be used for fee estimation" ,
} ,
cli . Int64Flag {
Name : "sat_per_byte" ,
Usage : "(optional) a manual fee expressed in sat/byte that should be " +
"used when crafting the transaction" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( sendMany ) ,
2015-12-30 05:31:03 +03:00
}
2016-06-29 23:01:08 +03:00
func sendMany ( ctx * cli . Context ) error {
2015-12-30 05:31:03 +03:00
var amountToAddr map [ string ] int64
2017-03-03 01:23:16 +03:00
jsonMap := ctx . Args ( ) . First ( )
2015-12-30 05:31:03 +03:00
if err := json . Unmarshal ( [ ] byte ( jsonMap ) , & amountToAddr ) ; err != nil {
2016-06-29 23:01:08 +03:00
return err
2015-12-30 05:31:03 +03:00
}
2017-11-23 22:40:14 +03:00
if ctx . IsSet ( "conf_target" ) && ctx . IsSet ( "sat_per_byte" ) {
return fmt . Errorf ( "either conf_target or sat_per_byte should be " +
"set, but not both" )
}
2015-12-30 05:31:03 +03:00
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2015-12-30 05:31:03 +03:00
2017-02-23 22:09:34 +03:00
txid , err := client . SendMany ( ctxb , & lnrpc . SendManyRequest {
AddrToAmount : amountToAddr ,
2017-11-23 22:40:14 +03:00
TargetConf : int32 ( ctx . Int64 ( "conf_target" ) ) ,
SatPerByte : ctx . Int64 ( "sat_per_byte" ) ,
2017-02-23 22:09:34 +03:00
} )
2015-12-30 05:31:03 +03:00
if err != nil {
2016-06-29 23:01:08 +03:00
return err
2015-12-30 05:31:03 +03:00
}
2017-02-23 22:56:47 +03:00
printRespJSON ( txid )
2016-06-29 23:01:08 +03:00
return nil
2015-12-30 05:31:03 +03:00
}
2016-01-17 06:10:29 +03:00
2017-02-24 16:32:33 +03:00
var connectCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "connect" ,
2018-02-06 02:05:04 +03:00
Usage : "Connect to a remote lnd peer" ,
2017-03-03 01:23:16 +03:00
ArgsUsage : "<pubkey>@host" ,
2017-01-10 06:09:45 +03:00
Flags : [ ] cli . Flag {
cli . BoolFlag {
Name : "perm" ,
2017-03-03 01:23:16 +03:00
Usage : "If set, the daemon will attempt to persistently " +
"connect to the target peer.\n" +
" If not, the call will be synchronous." ,
2017-01-10 06:09:45 +03:00
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( connectPeer ) ,
2016-01-17 06:10:29 +03:00
}
2016-06-29 23:01:08 +03:00
func connectPeer ( ctx * cli . Context ) error {
2016-01-17 06:10:29 +03:00
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-01-17 06:10:29 +03:00
2017-03-03 01:23:16 +03:00
targetAddress := ctx . Args ( ) . First ( )
2016-06-21 22:35:07 +03:00
splitAddr := strings . Split ( targetAddress , "@" )
2016-07-17 03:43:27 +03:00
if len ( splitAddr ) != 2 {
2016-10-28 05:42:47 +03:00
return fmt . Errorf ( "target address expected in format: " +
"pubkey@host:port" )
2016-07-17 03:43:27 +03:00
}
2016-06-21 22:35:07 +03:00
addr := & lnrpc . LightningAddress {
2016-10-28 05:42:47 +03:00
Pubkey : splitAddr [ 0 ] ,
Host : splitAddr [ 1 ] ,
2016-06-21 22:35:07 +03:00
}
2017-01-10 06:09:45 +03:00
req := & lnrpc . ConnectPeerRequest {
Addr : addr ,
Perm : ctx . Bool ( "perm" ) ,
}
2016-01-17 06:10:29 +03:00
lnid , err := client . ConnectPeer ( ctxb , req )
2017-05-05 15:05:30 +03:00
if err != nil {
return err
}
printRespJSON ( lnid )
return nil
}
var disconnectCommand = cli . Command {
Name : "disconnect" ,
2018-02-06 02:05:04 +03:00
Usage : "Disconnect a remote lnd peer identified by public key" ,
2017-05-05 15:05:30 +03:00
ArgsUsage : "<pubkey>" ,
2017-05-06 01:54:25 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "node_key" ,
Usage : "The hex-encoded compressed public key of the peer " +
"to disconnect from" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( disconnectPeer ) ,
2017-05-05 15:05:30 +03:00
}
func disconnectPeer ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2017-05-06 01:54:25 +03:00
var pubKey string
switch {
case ctx . IsSet ( "node_key" ) :
pubKey = ctx . String ( "node_key" )
case ctx . Args ( ) . Present ( ) :
pubKey = ctx . Args ( ) . First ( )
default :
return fmt . Errorf ( "must specify target public key" )
2017-05-05 15:05:30 +03:00
}
req := & lnrpc . DisconnectPeerRequest {
PubKey : pubKey ,
}
lnid , err := client . DisconnectPeer ( ctxb , req )
2016-01-17 06:10:29 +03:00
if err != nil {
2016-06-29 23:01:08 +03:00
return err
2016-01-17 06:10:29 +03:00
}
2017-02-23 22:56:47 +03:00
printRespJSON ( lnid )
2016-06-29 23:01:08 +03:00
return nil
2016-01-17 06:10:29 +03:00
}
2016-06-21 22:35:07 +03:00
2017-03-03 01:23:16 +03:00
// TODO(roasbeef): change default number of confirmations
2017-02-24 16:32:33 +03:00
var openChannelCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "openchannel" ,
2018-01-10 10:27:49 +03:00
Usage : "Open a channel to a node or an existing peer." ,
2017-11-23 22:40:14 +03:00
Description : `
Attempt to open a new channel to an existing peer with the key node - key
optionally blocking until the channel is ' open ' .
2018-01-10 10:27:49 +03:00
One can also connect to a node before opening a new channel to it by
setting its host : port via the -- connect argument . For this to work ,
the node_key must be provided , rather than the peer_id . This is optional .
2017-11-23 22:40:14 +03:00
The channel will be initialized with local - amt satoshis local and push - amt
2018-01-10 10:27:49 +03:00
satoshis for the remote node . Once the channel is open , a channelPoint ( txid : vout )
of the funding output is returned .
2017-11-23 22:40:14 +03:00
One can manually set the fee to be used for the funding transaction via either
2018-02-14 08:23:01 +03:00
the -- conf_target or -- sat_per_byte arguments . This is optional . ` ,
2017-07-31 00:23:29 +03:00
ArgsUsage : "node-key local-amt push-amt" ,
2016-06-21 22:35:07 +03:00
Flags : [ ] cli . Flag {
2016-09-14 01:36:27 +03:00
cli . StringFlag {
2016-10-28 05:42:47 +03:00
Name : "node_key" ,
2018-01-10 10:27:49 +03:00
Usage : "the identity public key of the target node/peer " +
2016-10-28 05:42:47 +03:00
"serialized in compressed format" ,
2016-06-21 22:35:07 +03:00
} ,
2018-01-10 10:27:49 +03:00
cli . StringFlag {
Name : "connect" ,
Usage : "(optional) the host:port of the target node" ,
} ,
2016-06-21 22:35:07 +03:00
cli . IntFlag {
Name : "local_amt" ,
Usage : "the number of satoshis the wallet should commit to the channel" ,
} ,
cli . IntFlag {
2017-01-10 06:06:07 +03:00
Name : "push_amt" ,
Usage : "the number of satoshis to push to the remote " +
"side as part of the initial commitment state" ,
2016-06-21 22:35:07 +03:00
} ,
2016-07-08 01:35:06 +03:00
cli . BoolFlag {
Name : "block" ,
Usage : "block and wait until the channel is fully open" ,
} ,
2017-11-23 22:40:14 +03:00
cli . Int64Flag {
Name : "conf_target" ,
Usage : "(optional) the number of blocks that the " +
"transaction *should* confirm in, will be " +
"used for fee estimation" ,
} ,
cli . Int64Flag {
Name : "sat_per_byte" ,
Usage : "(optional) a manual fee expressed in " +
"sat/byte that should be used when crafting " +
"the transaction" ,
} ,
2017-11-14 04:08:22 +03:00
cli . BoolFlag {
Name : "private" ,
Usage : "make the channel private, such that it won't " +
"be announced to the greater network, and " +
"nodes other than the two channel endpoints " +
"must be explicitly told about it to be able " +
"to route through it" ,
} ,
2017-12-17 01:57:31 +03:00
cli . Int64Flag {
Name : "min_htlc_msat" ,
Usage : "(optional) the minimum value we will require " +
"for incoming HTLCs on the channel" ,
} ,
2016-06-21 22:35:07 +03:00
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( openChannel ) ,
2016-06-21 22:35:07 +03:00
}
2016-06-29 23:01:08 +03:00
func openChannel ( ctx * cli . Context ) error {
2016-06-21 22:35:07 +03:00
// TODO(roasbeef): add deadline to context
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2017-03-03 22:33:16 +03:00
2017-03-03 01:23:16 +03:00
args := ctx . Args ( )
var err error
// Show command help if no arguments provided
if ctx . NArg ( ) == 0 && ctx . NumFlags ( ) == 0 {
cli . ShowCommandHelp ( ctx , "openchannel" )
return nil
}
2016-06-21 22:35:07 +03:00
2017-11-23 22:40:14 +03:00
req := & lnrpc . OpenChannelRequest {
2017-12-17 01:57:31 +03:00
TargetConf : int32 ( ctx . Int64 ( "conf_target" ) ) ,
SatPerByte : ctx . Int64 ( "sat_per_byte" ) ,
MinHtlcMsat : ctx . Int64 ( "min_htlc_msat" ) ,
2017-11-23 22:40:14 +03:00
}
2016-06-21 22:35:07 +03:00
2017-03-03 01:23:16 +03:00
switch {
case ctx . IsSet ( "node_key" ) :
2016-10-28 05:42:47 +03:00
nodePubHex , err := hex . DecodeString ( ctx . String ( "node_key" ) )
2016-09-14 01:36:27 +03:00
if err != nil {
2017-03-03 01:23:16 +03:00
return fmt . Errorf ( "unable to decode node public key: %v" , err )
2016-09-14 01:36:27 +03:00
}
2016-10-28 05:42:47 +03:00
req . NodePubkey = nodePubHex
2018-01-10 10:27:49 +03:00
2017-03-03 01:23:16 +03:00
case args . Present ( ) :
nodePubHex , err := hex . DecodeString ( args . First ( ) )
if err != nil {
return fmt . Errorf ( "unable to decode node public key: %v" , err )
}
args = args . Tail ( )
req . NodePubkey = nodePubHex
default :
2017-03-03 22:33:16 +03:00
return fmt . Errorf ( "node id argument missing" )
2017-03-03 01:23:16 +03:00
}
2018-01-10 10:27:49 +03:00
// As soon as we can confirm that the node's node_key was set, rather
// than the peer_id, we can check if the host:port was also set to
// connect to it before opening the channel.
if req . NodePubkey != nil && ctx . IsSet ( "connect" ) {
addr := & lnrpc . LightningAddress {
Pubkey : hex . EncodeToString ( req . NodePubkey ) ,
Host : ctx . String ( "connect" ) ,
}
req := & lnrpc . ConnectPeerRequest {
Addr : addr ,
Perm : false ,
}
// Check if connecting to the node was successful.
// We discard the peer id returned as it is not needed.
_ , err := client . ConnectPeer ( ctxb , req )
if err != nil &&
! strings . Contains ( err . Error ( ) , "already connected" ) {
return err
}
}
2017-03-03 01:23:16 +03:00
switch {
case ctx . IsSet ( "local_amt" ) :
req . LocalFundingAmount = int64 ( ctx . Int ( "local_amt" ) )
case args . Present ( ) :
req . LocalFundingAmount , err = strconv . ParseInt ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode local amt: %v" , err )
}
args = args . Tail ( )
default :
return fmt . Errorf ( "local amt argument missing" )
}
2017-03-03 22:33:16 +03:00
if ctx . IsSet ( "push_amt" ) {
2017-03-03 01:23:16 +03:00
req . PushSat = int64 ( ctx . Int ( "push_amt" ) )
2017-03-03 22:33:16 +03:00
} else if args . Present ( ) {
2017-03-03 01:23:16 +03:00
req . PushSat , err = strconv . ParseInt ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode push amt: %v" , err )
}
2016-09-14 01:36:27 +03:00
}
2017-11-14 04:08:22 +03:00
req . Private = ctx . Bool ( "private" )
2016-07-08 01:35:06 +03:00
stream , err := client . OpenChannel ( ctxb , req )
2016-06-21 22:35:07 +03:00
if err != nil {
2016-06-29 23:01:08 +03:00
return err
2016-06-21 22:35:07 +03:00
}
2016-07-08 01:35:06 +03:00
for {
resp , err := stream . Recv ( )
if err == io . EOF {
return nil
} else if err != nil {
return err
}
2016-08-31 02:54:49 +03:00
switch update := resp . Update . ( type ) {
2017-02-08 06:36:15 +03:00
case * lnrpc . OpenStatusUpdate_ChanPending :
txid , err := chainhash . NewHash ( update . ChanPending . Txid )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printJSON ( struct {
2017-02-08 06:36:15 +03:00
FundingTxid string ` json:"funding_txid" `
} {
FundingTxid : txid . String ( ) ,
} ,
)
if ! ctx . Bool ( "block" ) {
return nil
}
2016-08-31 02:54:49 +03:00
case * lnrpc . OpenStatusUpdate_ChanOpen :
channelPoint := update . ChanOpen . ChannelPoint
2018-01-11 07:59:30 +03:00
// A channel point's funding txid can be get/set as a
// byte slice or a string. In the case it is a string,
// decode it.
var txidHash [ ] byte
switch channelPoint . GetFundingTxid ( ) . ( type ) {
case * lnrpc . ChannelPoint_FundingTxidBytes :
txidHash = channelPoint . GetFundingTxidBytes ( )
case * lnrpc . ChannelPoint_FundingTxidStr :
s := channelPoint . GetFundingTxidStr ( )
h , err := chainhash . NewHashFromStr ( s )
if err != nil {
return err
}
txidHash = h [ : ]
}
txid , err := chainhash . NewHash ( txidHash )
2016-08-31 02:54:49 +03:00
if err != nil {
return err
}
index := channelPoint . OutputIndex
2017-02-23 22:56:47 +03:00
printJSON ( struct {
2016-08-31 02:54:49 +03:00
ChannelPoint string ` json:"channel_point" `
} {
ChannelPoint : fmt . Sprintf ( "%v:%v" , txid , index ) ,
} ,
)
2016-07-08 01:35:06 +03:00
}
2016-06-21 22:35:07 +03:00
}
}
// TODO(roasbeef): also allow short relative channel ID.
2017-02-23 22:56:47 +03:00
2017-02-24 16:32:33 +03:00
var closeChannelCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "closechannel" ,
Usage : "Close an existing channel." ,
2017-11-23 22:40:14 +03:00
Description : `
2018-01-24 05:34:29 +03:00
Close an existing channel . The channel can be closed either cooperatively ,
2017-11-23 22:40:14 +03:00
or unilaterally ( -- force ) .
2018-01-24 05:34:29 +03:00
2017-11-23 22:40:14 +03:00
A unilateral channel closure means that the latest commitment
transaction will be broadcast to the network . As a result , any settled
2018-01-24 05:34:29 +03:00
funds will be time locked for a few blocks before they can be spent .
2017-11-23 22:40:14 +03:00
In the case of a cooperative closure , One can manually set the fee to
be used for the closing transaction via either the -- conf_target or
-- sat_per_byte arguments . This will be the starting value used during
2018-01-24 05:34:29 +03:00
fee negotiation . This is optional . ` ,
2017-03-03 01:23:16 +03:00
ArgsUsage : "funding_txid [output_index [time_limit]]" ,
2016-06-21 22:35:07 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "funding_txid" ,
Usage : "the txid of the channel's funding transaction" ,
} ,
cli . IntFlag {
Name : "output_index" ,
Usage : "the output index for the funding output of the funding " +
"transaction" ,
} ,
cli . StringFlag {
Name : "time_limit" ,
Usage : "a relative deadline afterwhich the attempt should be " +
2017-04-27 07:38:53 +03:00
"abandoned" ,
2016-06-21 22:35:07 +03:00
} ,
cli . BoolFlag {
Name : "force" ,
2016-09-12 22:28:28 +03:00
Usage : "after the time limit has passed, attempt an " +
2016-06-21 22:35:07 +03:00
"uncooperative closure" ,
} ,
2016-07-08 01:35:06 +03:00
cli . BoolFlag {
Name : "block" ,
Usage : "block until the channel is closed" ,
} ,
2017-11-23 22:40:14 +03:00
cli . Int64Flag {
Name : "conf_target" ,
Usage : "(optional) the number of blocks that the " +
"transaction *should* confirm in, will be " +
"used for fee estimation" ,
} ,
cli . Int64Flag {
Name : "sat_per_byte" ,
Usage : "(optional) a manual fee expressed in " +
"sat/byte that should be used when crafting " +
"the transaction" ,
} ,
2016-06-21 22:35:07 +03:00
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( closeChannel ) ,
2016-06-21 22:35:07 +03:00
}
2016-06-29 23:01:08 +03:00
func closeChannel ( ctx * cli . Context ) error {
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-06-21 22:35:07 +03:00
2018-01-24 05:34:29 +03:00
// Show command help if no arguments and flags were provided.
2017-03-03 01:23:16 +03:00
if ctx . NArg ( ) == 0 && ctx . NumFlags ( ) == 0 {
2017-12-26 04:06:21 +03:00
cli . ShowCommandHelp ( ctx , "closechannel" )
2017-03-03 01:23:16 +03:00
return nil
2016-06-21 22:35:07 +03:00
}
2016-09-12 22:28:28 +03:00
// TODO(roasbeef): implement time deadline within server
2016-06-21 22:35:07 +03:00
req := & lnrpc . CloseChannelRequest {
2017-03-03 01:23:16 +03:00
ChannelPoint : & lnrpc . ChannelPoint { } ,
Force : ctx . Bool ( "force" ) ,
2017-11-23 22:40:14 +03:00
TargetConf : int32 ( ctx . Int64 ( "conf_target" ) ) ,
SatPerByte : ctx . Int64 ( "sat_per_byte" ) ,
2017-03-03 01:23:16 +03:00
}
2018-01-24 05:34:29 +03:00
args := ctx . Args ( )
2017-03-03 01:23:16 +03:00
switch {
case ctx . IsSet ( "funding_txid" ) :
2018-01-24 05:34:29 +03:00
req . ChannelPoint . FundingTxid = & lnrpc . ChannelPoint_FundingTxidStr {
FundingTxidStr : ctx . String ( "funding_txid" ) ,
}
2017-03-03 01:23:16 +03:00
case args . Present ( ) :
2018-01-24 05:34:29 +03:00
req . ChannelPoint . FundingTxid = & lnrpc . ChannelPoint_FundingTxidStr {
FundingTxidStr : args . First ( ) ,
}
2017-03-03 01:23:16 +03:00
args = args . Tail ( )
default :
return fmt . Errorf ( "funding txid argument missing" )
}
switch {
case ctx . IsSet ( "output_index" ) :
req . ChannelPoint . OutputIndex = uint32 ( ctx . Int ( "output_index" ) )
case args . Present ( ) :
2018-01-24 05:34:29 +03:00
index , err := strconv . ParseUint ( args . First ( ) , 10 , 32 )
2017-03-03 01:23:16 +03:00
if err != nil {
return fmt . Errorf ( "unable to decode output index: %v" , err )
}
req . ChannelPoint . OutputIndex = uint32 ( index )
default :
req . ChannelPoint . OutputIndex = 0
2016-06-21 22:35:07 +03:00
}
2018-01-24 05:34:29 +03:00
// After parsing the request, we'll spin up a goroutine that will
// retrieve the closing transaction ID when attempting to close the
// channel. We do this to because `executeChannelClose` can block, so we
// would like to present the closing transaction ID to the user as soon
// as it is broadcasted.
var wg sync . WaitGroup
txidChan := make ( chan string , 1 )
wg . Add ( 1 )
go func ( ) {
defer wg . Done ( )
printJSON ( struct {
ClosingTxid string ` json:"closing_txid" `
} {
ClosingTxid : <- txidChan ,
} )
} ( )
err := executeChannelClose ( client , req , txidChan , ctx . Bool ( "block" ) )
if err != nil {
return err
}
// In the case that the user did not provide the `block` flag, then we
// need to wait for the goroutine to be done to prevent it from being
// destroyed when exiting before printing the closing transaction ID.
wg . Wait ( )
return nil
}
// executeChannelClose attempts to close the channel from a request. The closing
// transaction ID is sent through `txidChan` as soon as it is broadcasted to the
// network. The block boolean is used to determine if we should block until the
// closing transaction receives all of its required confirmations.
func executeChannelClose ( client lnrpc . LightningClient , req * lnrpc . CloseChannelRequest ,
txidChan chan <- string , block bool ) error {
stream , err := client . CloseChannel ( context . Background ( ) , req )
2016-06-21 22:35:07 +03:00
if err != nil {
2016-06-29 23:01:08 +03:00
return err
2016-06-21 22:35:07 +03:00
}
2016-07-08 01:35:06 +03:00
for {
resp , err := stream . Recv ( )
if err == io . EOF {
return nil
} else if err != nil {
return err
}
2016-08-31 02:54:49 +03:00
switch update := resp . Update . ( type ) {
2017-02-08 06:36:15 +03:00
case * lnrpc . CloseStatusUpdate_ClosePending :
closingHash := update . ClosePending . Txid
txid , err := chainhash . NewHash ( closingHash )
if err != nil {
return err
}
2018-01-24 05:34:29 +03:00
txidChan <- txid . String ( )
2017-02-08 06:36:15 +03:00
2018-01-24 05:34:29 +03:00
if ! block {
2017-02-08 06:36:15 +03:00
return nil
}
2016-08-31 02:54:49 +03:00
case * lnrpc . CloseStatusUpdate_ChanClose :
2018-01-24 05:34:29 +03:00
return nil
}
}
}
var closeAllChannelsCommand = cli . Command {
Name : "closeallchannels" ,
Usage : "Close all existing channels." ,
Description : `
Close all existing channels .
Channels will be closed either cooperatively or unilaterally , depending
on whether the channel is active or not . If the channel is inactive , any
settled funds within it will be time locked for a few blocks before they
can be spent .
One can request to close inactive channels only by using the
-- inactive_only flag .
By default , one is prompted for confirmation every time an inactive
channel is requested to be closed . To avoid this , one can set the
-- force flag , which will only prompt for confirmation once for all
inactive channels and proceed to close them . ` ,
Flags : [ ] cli . Flag {
cli . BoolFlag {
Name : "inactive_only" ,
Usage : "close inactive channels only" ,
} ,
cli . BoolFlag {
Name : "force" ,
Usage : "ask for confirmation once before attempting " +
"to close existing channels" ,
} ,
} ,
Action : actionDecorator ( closeAllChannels ) ,
}
func closeAllChannels ( ctx * cli . Context ) error {
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
listReq := & lnrpc . ListChannelsRequest { }
openChannels , err := client . ListChannels ( context . Background ( ) , listReq )
if err != nil {
return fmt . Errorf ( "unable to fetch open channels: %v" , err )
}
if len ( openChannels . Channels ) == 0 {
return errors . New ( "no open channels to close" )
}
var channelsToClose [ ] * lnrpc . ActiveChannel
switch {
case ctx . Bool ( "force" ) && ctx . Bool ( "inactive_only" ) :
msg := "Unilaterally close all inactive channels? The funds " +
"within these channels will be locked for some blocks " +
"(CSV delay) before they can be spent. (yes/no): "
confirmed := promptForConfirmation ( msg )
// We can safely exit if the user did not confirm.
if ! confirmed {
return nil
}
// Go through the list of open channels and only add inactive
// channels to the closing list.
for _ , channel := range openChannels . Channels {
if ! channel . GetActive ( ) {
channelsToClose = append (
channelsToClose , channel ,
)
}
}
case ctx . Bool ( "force" ) :
msg := "Close all active and inactive channels? Inactive " +
"channels will be closed unilaterally, so funds " +
"within them will be locked for a few blocks (CSV " +
"delay) before they can be spent. (yes/no): "
confirmed := promptForConfirmation ( msg )
// We can safely exit if the user did not confirm.
if ! confirmed {
return nil
}
channelsToClose = openChannels . Channels
default :
// Go through the list of open channels and determine which
// should be added to the closing list.
for _ , channel := range openChannels . Channels {
// If the channel is inactive, we'll attempt to
// unilaterally close the channel, so we should prompt
// the user for confirmation beforehand.
if ! channel . GetActive ( ) {
msg := fmt . Sprintf ( "Unilaterally close channel " +
"with node %s and channel point %s? " +
"The closing transaction will need %d " +
"confirmations before the funds can be " +
"spent. (yes/no): " , channel . RemotePubkey ,
channel . ChannelPoint , channel . CsvDelay )
confirmed := promptForConfirmation ( msg )
if confirmed {
channelsToClose = append (
channelsToClose , channel ,
)
}
} else if ! ctx . Bool ( "inactive_only" ) {
// Otherwise, we'll only add active channels if
// we were not requested to close inactive
// channels only.
channelsToClose = append (
channelsToClose , channel ,
)
}
}
}
// result defines the result of closing a channel. The closing
// transaction ID is populated if a channel is successfully closed.
// Otherwise, the error that prevented closing the channel is populated.
type result struct {
RemotePubKey string ` json:"remote_pub_key" `
ChannelPoint string ` json:"channel_point" `
ClosingTxid string ` json:"closing_txid" `
FailErr string ` json:"error" `
}
// Launch each channel closure in a goroutine in order to execute them
// in parallel. Once they're all executed, we will print the results as
// they come.
resultChan := make ( chan result , len ( channelsToClose ) )
for _ , channel := range channelsToClose {
go func ( channel * lnrpc . ActiveChannel ) {
res := result { }
res . RemotePubKey = channel . RemotePubkey
res . ChannelPoint = channel . ChannelPoint
defer func ( ) {
resultChan <- res
} ( )
// Parse the channel point in order to create the close
// channel request.
s := strings . Split ( res . ChannelPoint , ":" )
if len ( s ) != 2 {
res . FailErr = "expected channel point with " +
"format txid:index"
return
}
index , err := strconv . ParseUint ( s [ 1 ] , 10 , 32 )
2016-08-31 02:54:49 +03:00
if err != nil {
2018-01-24 05:34:29 +03:00
res . FailErr = fmt . Sprintf ( "unable to parse " +
"channel point output index: %v" , err )
return
2016-08-31 02:54:49 +03:00
}
2018-01-24 05:34:29 +03:00
req := & lnrpc . CloseChannelRequest {
ChannelPoint : & lnrpc . ChannelPoint {
FundingTxid : & lnrpc . ChannelPoint_FundingTxidStr {
FundingTxidStr : s [ 0 ] ,
} ,
OutputIndex : uint32 ( index ) ,
} ,
Force : ! channel . GetActive ( ) ,
}
txidChan := make ( chan string , 1 )
err = executeChannelClose ( client , req , txidChan , false )
if err != nil {
res . FailErr = fmt . Sprintf ( "unable to close " +
"channel: %v" , err )
return
}
res . ClosingTxid = <- txidChan
} ( channel )
}
for range channelsToClose {
res := <- resultChan
printJSON ( res )
}
return nil
}
// promptForConfirmation continuously prompts the user for the message until
// receiving a response of "yes" or "no" and returns their answer as a bool.
func promptForConfirmation ( msg string ) bool {
reader := bufio . NewReader ( os . Stdin )
for {
fmt . Print ( msg )
answer , err := reader . ReadString ( '\n' )
if err != nil {
return false
}
answer = strings . ToLower ( strings . TrimSpace ( answer ) )
switch {
case answer == "yes" :
return true
case answer == "no" :
return false
default :
continue
2016-08-31 02:54:49 +03:00
}
2016-07-08 01:35:06 +03:00
}
2016-06-21 22:35:07 +03:00
}
2017-02-24 16:32:33 +03:00
var listPeersCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "listpeers" ,
Usage : "List all active, currently connected peers." ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( listPeers ) ,
2016-06-21 22:35:07 +03:00
}
2016-06-29 23:01:08 +03:00
func listPeers ( ctx * cli . Context ) error {
2016-06-21 22:35:07 +03:00
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-06-21 22:35:07 +03:00
req := & lnrpc . ListPeersRequest { }
resp , err := client . ListPeers ( ctxb , req )
if err != nil {
2016-06-29 23:01:08 +03:00
return err
2016-06-21 22:35:07 +03:00
}
2017-02-23 22:56:47 +03:00
printRespJSON ( resp )
2016-06-29 23:01:08 +03:00
return nil
2016-06-21 22:35:07 +03:00
}
2017-10-12 12:42:06 +03:00
var createCommand = cli . Command {
2018-02-02 07:52:40 +03:00
Name : "create" ,
Description : `
The create command is used to initialize an lnd wallet from scratch for
the very first time . This is interactive command with one required
argument ( the password ) , and one optional argument ( the mnemonic
passphrase ) .
The first argument ( the password ) is required and MUST be greater than
8 characters . This will be used to encrypt the wallet within lnd . This
MUST be remembered as it will be required to fully start up the daemon .
The second argument is an optional 24 - word mnemonic derived from BIP
39. If provided , then the internal wallet will use the seed derived
from this mnemonic to generate all keys .
This command returns a 24 - word seed in the scenario that NO mnemonic
was provided by the user . This should be written down as it can be used
to potentially recover all on - chain funds , and most off - chain funds as
well .
` ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( create ) ,
2017-10-12 12:42:06 +03:00
}
2018-02-02 07:52:40 +03:00
// monowidthColumns takes a set of words, and the number of desired columns,
// and returns a new set of words that have had white space appended to the
// word in order to create a mono-width column.
func monowidthColumns ( words [ ] string , ncols int ) [ ] string {
// Determine max size of words in each column.
colWidths := make ( [ ] int , ncols )
for i , word := range words {
col := i % ncols
curWidth := colWidths [ col ]
if len ( word ) > curWidth {
colWidths [ col ] = len ( word )
}
}
// Append whitespace to each word to make columns mono-width.
finalWords := make ( [ ] string , len ( words ) )
for i , word := range words {
col := i % ncols
width := colWidths [ col ]
diff := width - len ( word )
finalWords [ i ] = word + strings . Repeat ( " " , diff )
}
return finalWords
}
2017-10-12 12:42:06 +03:00
func create ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getWalletUnlockerClient ( ctx )
defer cleanUp ( )
2018-02-02 07:52:40 +03:00
// First, we'll prompt the user for their passphrase twice to ensure
// both attempts match up properly.
2017-10-12 12:42:06 +03:00
fmt . Printf ( "Input wallet password: " )
2017-12-19 01:04:04 +03:00
pw1 , err := terminal . ReadPassword ( int ( syscall . Stdin ) )
2017-10-12 12:42:06 +03:00
if err != nil {
return err
}
fmt . Println ( )
fmt . Printf ( "Confirm wallet password: " )
2017-12-19 01:04:04 +03:00
pw2 , err := terminal . ReadPassword ( int ( syscall . Stdin ) )
2017-10-12 12:42:06 +03:00
if err != nil {
return err
}
fmt . Println ( )
2018-02-02 07:52:40 +03:00
// If the passwords don't match, then we'll return an error.
2017-10-12 12:42:06 +03:00
if ! bytes . Equal ( pw1 , pw2 ) {
return fmt . Errorf ( "passwords don't match" )
}
2018-02-02 07:52:40 +03:00
// Next, we'll see if the user has 24-word mnemonic they want to use to
// derive a seed within the wallet.
var (
hasMnemonic bool
)
mnemonicCheck :
for {
fmt . Println ( )
fmt . Printf ( "Do you have an existing cipher seed " +
"mnemonic you want to use? (Enter y/n): " )
reader := bufio . NewReader ( os . Stdin )
answer , err := reader . ReadString ( '\n' )
if err != nil {
return err
}
fmt . Println ( )
answer = strings . TrimSpace ( answer )
answer = strings . ToLower ( answer )
switch answer {
case "y" :
hasMnemonic = true
break mnemonicCheck
case "n" :
hasMnemonic = false
break mnemonicCheck
}
2017-10-12 12:42:06 +03:00
}
2018-02-02 07:52:40 +03:00
// If the user *does* have an existing seed they want to use, then
// we'll read that in directly from the terminal.
var (
cipherSeedMnemonic [ ] string
aezeedPass [ ] byte
)
if hasMnemonic {
// We'll now prompt the user to enter in their 24-word
// mnemonic.
fmt . Printf ( "Input your 24-word mnemonic separated by spaces: " )
reader := bufio . NewReader ( os . Stdin )
mnemonic , err := reader . ReadString ( '\n' )
if err != nil {
return err
}
// We'll trim off extra spaces, and ensure the mnemonic is all
// lower case, then populate our request.
mnemonic = strings . TrimSpace ( mnemonic )
mnemonic = strings . ToLower ( mnemonic )
cipherSeedMnemonic = strings . Split ( mnemonic , " " )
fmt . Println ( )
2018-03-13 22:42:44 +03:00
if len ( cipherSeedMnemonic ) != 24 {
return fmt . Errorf ( "wrong cipher seed mnemonic " +
"length: got %v words, expecting %v words" ,
len ( CipherSeedMnemonic ) , 24 )
}
2018-02-02 07:52:40 +03:00
// Additionally, the user may have a passphrase, that will also
// need to be provided so the daemon can properly decipher the
// cipher seed.
fmt . Printf ( "Input your cipher seed passphrase (press enter if " +
"your seed doesn't have a passphrase): " )
passphrase , err := terminal . ReadPassword ( int ( syscall . Stdin ) )
if err != nil {
return err
}
aezeedPass = [ ] byte ( passphrase )
fmt . Println ( )
} else {
// Otherwise, if the user doesn't have a mnemonic that they
// want to use, we'll generate a fresh one with the GenSeed
// command.
fmt . Println ( "Your cipher seed can optionally be encrypted." )
fmt . Printf ( "Input your passphrase you wish to encrypt it " +
"(or press enter to proceed without a cipher seed " +
"passphrase): " )
aezeedPass1 , err := terminal . ReadPassword ( int ( syscall . Stdin ) )
if err != nil {
return err
}
fmt . Println ( )
if len ( aezeedPass1 ) != 0 {
fmt . Printf ( "Confirm cipher seed passphrase: " )
aezeedPass2 , err := terminal . ReadPassword (
int ( syscall . Stdin ) ,
)
if err != nil {
return err
}
fmt . Println ( )
// If the passwords don't match, then we'll return an
// error.
if ! bytes . Equal ( aezeedPass1 , aezeedPass2 ) {
return fmt . Errorf ( "cipher seed pass phrases " +
"don't match" )
}
}
fmt . Println ( )
fmt . Println ( "Generating fresh cipher seed..." )
fmt . Println ( )
genSeedReq := & lnrpc . GenSeedRequest {
AezeedPassphrase : aezeedPass1 ,
}
seedResp , err := client . GenSeed ( ctxb , genSeedReq )
if err != nil {
return fmt . Errorf ( "unable to generate seed: %v" , err )
}
cipherSeedMnemonic = seedResp . CipherSeedMnemonic
aezeedPass = aezeedPass1
}
// Before we initialize the wallet, we'll display the cipher seed to
// the user so they can write it down.
mnemonicWords := cipherSeedMnemonic
fmt . Println ( "!!!YOU MUST WRITE DOWN THIS SEED TO BE ABLE TO " +
"RESTORE THE WALLET!!!\n" )
fmt . Println ( "---------------BEGIN LND CIPHER SEED---------------" )
numCols := 4
colWords := monowidthColumns ( mnemonicWords , numCols )
for i := 0 ; i < len ( colWords ) ; i += numCols {
fmt . Printf ( "%2d. %3s %2d. %3s %2d. %3s %2d. %3s\n" ,
i + 1 , colWords [ i ] , i + 2 , colWords [ i + 1 ] , i + 3 ,
colWords [ i + 2 ] , i + 4 , colWords [ i + 3 ] )
}
fmt . Println ( "---------------END LND CIPHER SEED-----------------" )
fmt . Println ( "\n!!!YOU MUST WRITE DOWN THIS SEED TO BE ABLE TO " +
"RESTORE THE WALLET!!!" )
// With either the user's prior cipher seed, or a newly generated one,
// we'll go ahead and initialize the wallet.
req := & lnrpc . InitWalletRequest {
WalletPassword : pw1 ,
CipherSeedMnemonic : cipherSeedMnemonic ,
AezeedPassphrase : aezeedPass ,
}
if _ , err := client . InitWallet ( ctxb , req ) ; err != nil {
2017-10-12 12:42:06 +03:00
return err
}
2018-02-02 07:52:40 +03:00
fmt . Println ( "\nlnd successfully initialized!" )
2017-10-12 12:42:06 +03:00
return nil
}
var unlockCommand = cli . Command {
2018-02-02 07:52:40 +03:00
Name : "unlock" ,
Description : `
The unlock command is used to decrypt lnd ' s wallet state in order to
start up . This command MUST be run after booting up lnd before it ' s
able to carry out its duties . An exception is if a user is running with
-- noencryptwallet , then a default passphrase will be used .
` ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( unlock ) ,
2017-10-12 12:42:06 +03:00
}
func unlock ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getWalletUnlockerClient ( ctx )
defer cleanUp ( )
fmt . Printf ( "Input wallet password: " )
2017-12-19 01:04:04 +03:00
pw , err := terminal . ReadPassword ( int ( syscall . Stdin ) )
2017-10-12 12:42:06 +03:00
if err != nil {
return err
}
fmt . Println ( )
req := & lnrpc . UnlockWalletRequest {
2018-02-02 07:52:40 +03:00
WalletPassword : pw ,
2017-10-12 12:42:06 +03:00
}
_ , err = client . UnlockWallet ( ctxb , req )
if err != nil {
return err
}
2018-02-02 07:52:40 +03:00
fmt . Println ( "\nlnd successfully unlocked!" )
2017-10-12 12:42:06 +03:00
return nil
}
2017-02-24 16:32:33 +03:00
var walletBalanceCommand = cli . Command {
2018-02-18 02:42:17 +03:00
Name : "walletbalance" ,
Usage : "Compute and display the wallet's current balance" ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( walletBalance ) ,
2016-06-21 22:35:07 +03:00
}
2016-06-29 23:01:08 +03:00
func walletBalance ( ctx * cli . Context ) error {
2016-06-21 22:35:07 +03:00
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-06-21 22:35:07 +03:00
2018-02-18 02:42:17 +03:00
req := & lnrpc . WalletBalanceRequest { }
2016-06-21 22:35:07 +03:00
resp , err := client . WalletBalance ( ctxb , req )
if err != nil {
2016-06-29 23:01:08 +03:00
return err
2016-06-21 22:35:07 +03:00
}
2017-02-23 22:56:47 +03:00
printRespJSON ( resp )
2016-06-29 23:01:08 +03:00
return nil
2016-06-21 22:35:07 +03:00
}
2016-07-06 04:58:41 +03:00
2017-02-24 16:32:33 +03:00
var channelBalanceCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "channelbalance" ,
2018-02-06 02:05:04 +03:00
Usage : "Returns the sum of the total available channel balance across all open channels" ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( channelBalance ) ,
2016-09-15 21:59:51 +03:00
}
func channelBalance ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-09-15 21:59:51 +03:00
req := & lnrpc . ChannelBalanceRequest { }
resp , err := client . ChannelBalance ( ctxb , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( resp )
2016-09-15 21:59:51 +03:00
return nil
}
2017-02-24 16:32:33 +03:00
var getInfoCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "getinfo" ,
2018-02-06 02:05:04 +03:00
Usage : "Returns basic information related to the active daemon" ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( getInfo ) ,
2016-07-06 04:58:41 +03:00
}
func getInfo ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-07-06 04:58:41 +03:00
req := & lnrpc . GetInfoRequest { }
resp , err := client . GetInfo ( ctxb , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( resp )
2016-07-06 04:58:41 +03:00
return nil
}
2016-07-08 01:35:58 +03:00
2017-02-24 16:32:33 +03:00
var pendingChannelsCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "pendingchannels" ,
2018-02-06 02:05:04 +03:00
Usage : "Display information pertaining to pending channels" ,
2016-07-08 01:35:58 +03:00
Flags : [ ] cli . Flag {
cli . BoolFlag {
Name : "open, o" ,
Usage : "display the status of new pending channels" ,
} ,
cli . BoolFlag {
Name : "close, c" ,
Usage : "display the status of channels being closed" ,
} ,
cli . BoolFlag {
Name : "all, a" ,
Usage : "display the status of channels in the " +
"process of being opened or closed" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( pendingChannels ) ,
2016-07-08 01:35:58 +03:00
}
func pendingChannels ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-07-08 01:35:58 +03:00
2018-01-04 23:20:25 +03:00
req := & lnrpc . PendingChannelsRequest { }
2016-07-08 01:35:58 +03:00
resp , err := client . PendingChannels ( ctxb , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( resp )
2016-07-08 01:35:58 +03:00
return nil
}
2016-07-13 03:47:24 +03:00
2017-02-24 16:32:33 +03:00
var listChannelsCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "listchannels" ,
2018-02-06 02:05:04 +03:00
Usage : "List all open channels" ,
2016-09-26 06:04:58 +03:00
Flags : [ ] cli . Flag {
cli . BoolFlag {
Name : "active_only, a" ,
Usage : "only list channels which are currently active" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( listChannels ) ,
2016-09-26 06:04:58 +03:00
}
func listChannels ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-09-26 06:04:58 +03:00
req := & lnrpc . ListChannelsRequest { }
resp , err := client . ListChannels ( ctxb , req )
if err != nil {
return err
}
2017-01-18 00:39:30 +03:00
// TODO(roasbeef): defer close the client for the all
2017-02-23 22:56:47 +03:00
printRespJSON ( resp )
2016-09-26 06:04:58 +03:00
return nil
}
2017-02-24 16:32:33 +03:00
var sendPaymentCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "sendpayment" ,
2018-02-06 02:05:04 +03:00
Usage : "Send a payment over lightning" ,
2018-01-20 04:33:03 +03:00
Description : `
Send a payment over Lightning . One can either specify the full
parameters of the payment , or just use a payment request which encodes
all the payment details .
If payment isn ' t manually specified , then only a payment request needs
to be passed using the -- pay_req argument .
If the payment * is * manually specified , then all four alternative
arguments need to be specified in order to complete the payment :
* -- dest = N
* -- amt = A
2018-01-28 03:23:42 +03:00
* -- final_cltv_delta = T
2018-01-20 04:33:03 +03:00
* -- payment_hash = H
The -- debug_send flag is provided for usage * purely * in test
environments . If specified , then the payment hash isn ' t required , as
it ' ll use the hash of all zeroes . This mode allows one to quickly test
payment connectivity without having to create an invoice at the
destination .
` ,
ArgsUsage : "dest amt payment_hash final_cltv_delta | --pay_req=[payment request]" ,
2016-07-13 03:47:24 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
2016-09-21 02:19:15 +03:00
Name : "dest, d" ,
Usage : "the compressed identity pubkey of the " +
"payment recipient" ,
2016-07-13 03:47:24 +03:00
} ,
2017-03-03 01:23:16 +03:00
cli . Int64Flag {
2016-07-13 03:47:24 +03:00
Name : "amt, a" ,
Usage : "number of satoshis to send" ,
} ,
cli . StringFlag {
Name : "payment_hash, r" ,
Usage : "the hash to use within the payment's HTLC" ,
} ,
2016-09-21 02:14:45 +03:00
cli . BoolFlag {
Name : "debug_send" ,
Usage : "use the debug rHash when sending the HTLC" ,
} ,
2017-01-03 02:38:00 +03:00
cli . StringFlag {
Name : "pay_req" ,
2017-10-28 01:39:54 +03:00
Usage : "a zpay32 encoded payment request to fulfill" ,
2016-07-13 03:47:24 +03:00
} ,
2018-01-20 04:32:32 +03:00
cli . Int64Flag {
Name : "final_cltv_delta" ,
Usage : "the number of blocks the last hop has to reveal the preimage" ,
} ,
2016-07-13 03:47:24 +03:00
} ,
2017-02-24 16:32:33 +03:00
Action : sendPayment ,
2016-07-13 03:47:24 +03:00
}
2017-02-24 16:32:33 +03:00
func sendPayment ( ctx * cli . Context ) error {
2018-02-07 06:11:11 +03:00
// Show command help if no arguments provided
2017-03-03 01:23:16 +03:00
if ctx . NArg ( ) == 0 && ctx . NumFlags ( ) == 0 {
cli . ShowCommandHelp ( ctx , "sendpayment" )
return nil
}
2017-01-03 02:38:00 +03:00
var req * lnrpc . SendRequest
2017-03-03 01:23:16 +03:00
if ctx . IsSet ( "pay_req" ) {
2017-01-03 02:38:00 +03:00
req = & lnrpc . SendRequest {
PaymentRequest : ctx . String ( "pay_req" ) ,
2018-01-22 23:28:50 +03:00
Amt : ctx . Int64 ( "amt" ) ,
2017-01-03 02:38:00 +03:00
}
} else {
2017-03-03 01:23:16 +03:00
args := ctx . Args ( )
var (
destNode [ ] byte
err error
amount int64
)
switch {
case ctx . IsSet ( "dest" ) :
destNode , err = hex . DecodeString ( ctx . String ( "dest" ) )
case args . Present ( ) :
destNode , err = hex . DecodeString ( args . First ( ) )
args = args . Tail ( )
default :
return fmt . Errorf ( "destination txid argument missing" )
}
2016-09-21 02:14:45 +03:00
if err != nil {
return err
}
2017-03-03 01:23:16 +03:00
2017-01-03 02:38:00 +03:00
if len ( destNode ) != 33 {
return fmt . Errorf ( "dest node pubkey must be exactly 33 bytes, is " +
"instead: %v" , len ( destNode ) )
}
2017-03-03 01:23:16 +03:00
if ctx . IsSet ( "amt" ) {
amount = ctx . Int64 ( "amt" )
} else if args . Present ( ) {
amount , err = strconv . ParseInt ( args . First ( ) , 10 , 64 )
args = args . Tail ( )
if err != nil {
return fmt . Errorf ( "unable to decode payment amount: %v" , err )
}
}
2017-01-03 02:38:00 +03:00
req = & lnrpc . SendRequest {
Dest : destNode ,
2017-03-03 01:23:16 +03:00
Amt : amount ,
2017-01-03 02:38:00 +03:00
}
2017-03-03 01:23:16 +03:00
if ctx . Bool ( "debug_send" ) && ( ctx . IsSet ( "payment_hash" ) || args . Present ( ) ) {
return fmt . Errorf ( "do not provide a payment hash with debug send" )
} else if ! ctx . Bool ( "debug_send" ) {
var rHash [ ] byte
switch {
case ctx . IsSet ( "payment_hash" ) :
rHash , err = hex . DecodeString ( ctx . String ( "payment_hash" ) )
case args . Present ( ) :
rHash , err = hex . DecodeString ( args . First ( ) )
default :
return fmt . Errorf ( "payment hash argument missing" )
}
2017-01-03 02:38:00 +03:00
if err != nil {
return err
}
if len ( rHash ) != 32 {
return fmt . Errorf ( "payment hash must be exactly 32 " +
"bytes, is instead %v" , len ( rHash ) )
}
req . PaymentHash = rHash
2018-01-20 04:32:32 +03:00
switch {
case ctx . IsSet ( "final_cltv_delta" ) :
req . FinalCltvDelta = int32 ( ctx . Int64 ( "final_cltv_delta" ) )
case args . Present ( ) :
delta , err := strconv . ParseInt ( args . First ( ) , 10 , 64 )
if err != nil {
return err
}
req . FinalCltvDelta = int32 ( delta )
}
2016-09-21 02:14:45 +03:00
}
2016-07-13 03:47:24 +03:00
}
2017-10-28 01:39:54 +03:00
return sendPaymentRequest ( ctx , req )
}
func sendPaymentRequest ( ctx * cli . Context , req * lnrpc . SendRequest ) error {
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-07-13 03:47:24 +03:00
paymentStream , err := client . SendPayment ( context . Background ( ) )
if err != nil {
return err
}
if err := paymentStream . Send ( req ) ; err != nil {
return err
}
resp , err := paymentStream . Recv ( )
if err != nil {
return err
}
2016-07-22 02:18:42 +03:00
paymentStream . CloseSend ( )
2017-02-23 22:56:47 +03:00
printJSON ( struct {
2017-07-05 01:55:26 +03:00
E string ` json:"payment_error" `
2017-02-21 10:58:17 +03:00
P string ` json:"payment_preimage" `
R * lnrpc . Route ` json:"payment_route" `
} {
2017-07-05 01:55:26 +03:00
E : resp . PaymentError ,
2017-02-21 10:58:17 +03:00
P : hex . EncodeToString ( resp . PaymentPreimage ) ,
R : resp . PaymentRoute ,
} )
2016-07-13 03:47:24 +03:00
return nil
}
2016-07-15 14:02:59 +03:00
2017-10-28 01:39:54 +03:00
var payInvoiceCommand = cli . Command {
Name : "payinvoice" ,
2018-02-06 02:05:04 +03:00
Usage : "Pay an invoice over lightning" ,
2017-10-28 01:39:54 +03:00
ArgsUsage : "pay_req" ,
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "pay_req" ,
Usage : "a zpay32 encoded payment request to fulfill" ,
} ,
2018-01-22 23:28:50 +03:00
cli . Int64Flag {
Name : "amt" ,
Usage : "(optional) number of satoshis to fulfill the " +
"invoice" ,
} ,
2017-10-28 01:39:54 +03:00
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( payInvoice ) ,
2017-10-28 01:39:54 +03:00
}
func payInvoice ( ctx * cli . Context ) error {
args := ctx . Args ( )
var payReq string
switch {
case ctx . IsSet ( "pay_req" ) :
payReq = ctx . String ( "pay_req" )
case args . Present ( ) :
payReq = args . First ( )
default :
return fmt . Errorf ( "pay_req argument missing" )
}
req := & lnrpc . SendRequest {
PaymentRequest : payReq ,
2018-01-22 23:28:50 +03:00
Amt : ctx . Int64 ( "amt" ) ,
2017-10-28 01:39:54 +03:00
}
return sendPaymentRequest ( ctx , req )
}
2017-02-24 16:32:33 +03:00
var addInvoiceCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "addinvoice" ,
2018-02-06 02:05:04 +03:00
Usage : "Add a new invoice." ,
2017-11-23 22:40:14 +03:00
Description : `
Add a new invoice , expressing intent for a future payment .
2018-01-22 22:51:09 +03:00
Invoices without an amount can be created by not supplying any
parameters or providing an amount of 0. These invoices allow the payee
to specify the amount of satoshis they wish to send . ` ,
2017-03-03 01:23:16 +03:00
ArgsUsage : "value preimage" ,
2016-09-19 22:05:54 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
2017-09-05 19:11:04 +03:00
Name : "memo" ,
Usage : "a description of the payment to attach along " +
"with the invoice (default=\"\")" ,
2016-09-19 22:05:54 +03:00
} ,
cli . StringFlag {
Name : "receipt" ,
Usage : "an optional cryptographic receipt of payment" ,
} ,
cli . StringFlag {
2017-09-05 19:11:04 +03:00
Name : "preimage" ,
Usage : "the hex-encoded preimage (32 byte) which will " +
"allow settling an incoming HTLC payable to this " +
"preimage. If not set, a random preimage will be " +
"created." ,
2016-09-19 22:05:54 +03:00
} ,
2017-03-03 01:23:16 +03:00
cli . Int64Flag {
2018-01-18 21:32:24 +03:00
Name : "amt" ,
Usage : "the amt of satoshis in this invoice" ,
2016-09-19 22:05:54 +03:00
} ,
2017-09-05 19:11:04 +03:00
cli . StringFlag {
Name : "description_hash" ,
Usage : "SHA-256 hash of the description of the payment. " +
"Used if the purpose of payment cannot naturally " +
"fit within the memo. If provided this will be " +
"used instead of the description(memo) field in " +
"the encoded invoice." ,
} ,
cli . StringFlag {
Name : "fallback_addr" ,
Usage : "fallback on-chain address that can be used in " +
"case the lightning payment fails" ,
} ,
cli . Int64Flag {
Name : "expiry" ,
Usage : "the invoice's expiry time in seconds. If not " +
"specified an expiry of 3600 seconds (1 hour) " +
"is implied." ,
} ,
2016-09-19 22:05:54 +03:00
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( addInvoice ) ,
2016-09-19 22:05:54 +03:00
}
func addInvoice ( ctx * cli . Context ) error {
2017-03-03 01:23:16 +03:00
var (
preimage [ ] byte
2017-09-05 19:11:04 +03:00
descHash [ ] byte
2017-03-03 01:23:16 +03:00
receipt [ ] byte
2018-01-28 02:05:32 +03:00
amt int64
err error
2017-03-03 01:23:16 +03:00
)
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-09-19 22:05:54 +03:00
2017-03-03 01:23:16 +03:00
args := ctx . Args ( )
switch {
2018-01-18 21:32:24 +03:00
case ctx . IsSet ( "amt" ) :
amt = ctx . Int64 ( "amt" )
2017-03-03 01:23:16 +03:00
case args . Present ( ) :
2018-01-18 21:32:24 +03:00
amt , err = strconv . ParseInt ( args . First ( ) , 10 , 64 )
2017-03-03 01:23:16 +03:00
args = args . Tail ( )
if err != nil {
2018-01-18 21:32:24 +03:00
return fmt . Errorf ( "unable to decode amt argument: %v" , err )
2017-03-03 01:23:16 +03:00
}
}
switch {
case ctx . IsSet ( "preimage" ) :
preimage , err = hex . DecodeString ( ctx . String ( "preimage" ) )
case args . Present ( ) :
preimage , err = hex . DecodeString ( args . First ( ) )
}
2016-09-19 22:05:54 +03:00
if err != nil {
return fmt . Errorf ( "unable to parse preimage: %v" , err )
}
2017-09-05 19:11:04 +03:00
descHash , err = hex . DecodeString ( ctx . String ( "description_hash" ) )
if err != nil {
return fmt . Errorf ( "unable to parse description_hash: %v" , err )
}
2017-03-03 01:23:16 +03:00
receipt , err = hex . DecodeString ( ctx . String ( "receipt" ) )
2016-09-19 22:05:54 +03:00
if err != nil {
return fmt . Errorf ( "unable to parse receipt: %v" , err )
}
invoice := & lnrpc . Invoice {
2017-09-05 19:11:04 +03:00
Memo : ctx . String ( "memo" ) ,
Receipt : receipt ,
RPreimage : preimage ,
2018-01-18 21:32:24 +03:00
Value : amt ,
2017-09-05 19:11:04 +03:00
DescriptionHash : descHash ,
FallbackAddr : ctx . String ( "fallback_addr" ) ,
Expiry : ctx . Int64 ( "expiry" ) ,
2016-09-19 22:05:54 +03:00
}
resp , err := client . AddInvoice ( context . Background ( ) , invoice )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printJSON ( struct {
2017-01-03 02:37:10 +03:00
RHash string ` json:"r_hash" `
PayReq string ` json:"pay_req" `
2016-09-19 22:05:54 +03:00
} {
2017-01-03 02:37:10 +03:00
RHash : hex . EncodeToString ( resp . RHash ) ,
PayReq : resp . PaymentRequest ,
2016-09-19 22:05:54 +03:00
} )
return nil
}
2017-02-24 16:32:33 +03:00
var lookupInvoiceCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "lookupinvoice" ,
Usage : "Lookup an existing invoice by its payment hash." ,
ArgsUsage : "rhash" ,
2016-09-19 22:05:54 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "rhash" ,
2017-03-03 01:23:16 +03:00
Usage : "the 32 byte payment hash of the invoice to query for, the hash " +
2016-09-19 22:05:54 +03:00
"should be a hex-encoded string" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( lookupInvoice ) ,
2016-09-19 22:05:54 +03:00
}
func lookupInvoice ( ctx * cli . Context ) error {
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-09-19 22:05:54 +03:00
2017-03-03 01:23:16 +03:00
var (
rHash [ ] byte
err error
)
switch {
case ctx . IsSet ( "rhash" ) :
rHash , err = hex . DecodeString ( ctx . String ( "rhash" ) )
case ctx . Args ( ) . Present ( ) :
rHash , err = hex . DecodeString ( ctx . Args ( ) . First ( ) )
default :
return fmt . Errorf ( "rhash argument missing" )
}
2016-09-19 22:05:54 +03:00
if err != nil {
2017-03-03 01:23:16 +03:00
return fmt . Errorf ( "unable to decode rhash argument: %v" , err )
2016-09-19 22:05:54 +03:00
}
req := & lnrpc . PaymentHash {
RHash : rHash ,
}
invoice , err := client . LookupInvoice ( context . Background ( ) , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( invoice )
2016-09-19 22:05:54 +03:00
return nil
}
2017-02-24 16:32:33 +03:00
var listInvoicesCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "listinvoices" ,
Usage : "List all invoices currently stored." ,
2016-09-19 22:05:54 +03:00
Flags : [ ] cli . Flag {
cli . BoolFlag {
Name : "pending_only" ,
Usage : "toggles if all invoices should be returned, or only " +
"those that are currently unsettled" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( listInvoices ) ,
2016-09-19 22:05:54 +03:00
}
func listInvoices ( ctx * cli . Context ) error {
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-09-19 22:05:54 +03:00
pendingOnly := true
if ! ctx . Bool ( "pending_only" ) {
pendingOnly = false
}
req := & lnrpc . ListInvoiceRequest {
PendingOnly : pendingOnly ,
}
invoices , err := client . ListInvoices ( context . Background ( ) , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( invoices )
2016-09-19 22:05:54 +03:00
return nil
}
2017-02-24 16:32:33 +03:00
var describeGraphCommand = cli . Command {
2016-12-27 08:52:15 +03:00
Name : "describegraph" ,
2018-02-06 02:05:04 +03:00
Description : "Prints a human readable version of the known channel " +
2016-12-27 08:52:15 +03:00
"graph from the PoV of the node" ,
2018-02-06 02:05:04 +03:00
Usage : "Describe the network graph" ,
2017-01-24 07:32:17 +03:00
Flags : [ ] cli . Flag {
cli . BoolFlag {
2017-01-30 02:38:04 +03:00
Name : "render" ,
2017-03-03 01:23:16 +03:00
Usage : "If set, then an image of graph will be generated and displayed. The generated image is stored within the current directory with a file name of 'graph.svg'" ,
2017-01-24 07:32:17 +03:00
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( describeGraph ) ,
2016-08-31 02:54:49 +03:00
}
2016-08-20 23:49:35 +03:00
2016-12-27 08:52:15 +03:00
func describeGraph ( ctx * cli . Context ) error {
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-08-21 17:46:54 +03:00
2016-12-27 08:52:15 +03:00
req := & lnrpc . ChannelGraphRequest { }
2016-12-28 02:25:43 +03:00
2016-12-27 08:52:15 +03:00
graph , err := client . DescribeGraph ( context . Background ( ) , req )
2016-08-21 17:46:54 +03:00
if err != nil {
return err
}
2017-01-24 07:32:17 +03:00
// If the draw flag is on, then we'll use the 'dot' command to create a
// visualization of the graph itself.
2017-01-30 02:38:04 +03:00
if ctx . Bool ( "render" ) {
2017-01-24 07:32:17 +03:00
return drawChannelGraph ( graph )
}
2017-02-23 22:56:47 +03:00
printRespJSON ( graph )
2016-08-21 17:46:54 +03:00
return nil
}
2017-01-25 05:07:15 +03:00
// normalizeFunc is a factory function which returns a function that normalizes
// the capacity of of edges within the graph. The value of the returned
// function can be used to either plot the capacities, or to use a weight in a
// rendering of the graph.
func normalizeFunc ( edges [ ] * lnrpc . ChannelEdge , scaleFactor float64 ) func ( int64 ) float64 {
var (
min float64 = math . MaxInt64
max float64
)
for _ , edge := range edges {
// In order to obtain saner values, we reduce the capacity of a
2018-02-07 06:13:07 +03:00
// channel to its base 2 logarithm.
2017-01-25 05:07:15 +03:00
z := math . Log2 ( float64 ( edge . Capacity ) )
if z < min {
min = z
}
if z > max {
max = z
}
}
return func ( x int64 ) float64 {
y := math . Log2 ( float64 ( x ) )
2017-01-26 05:27:27 +03:00
// TODO(roasbeef): results in min being zero
2017-03-09 07:44:32 +03:00
return ( y - min ) / ( max - min ) * scaleFactor
2017-01-25 05:07:15 +03:00
}
}
2017-01-24 07:32:17 +03:00
func drawChannelGraph ( graph * lnrpc . ChannelGraph ) error {
// First we'll create a temporary file that we'll write the compiled
// string that describes our graph in the dot format to.
tempDotFile , err := ioutil . TempFile ( "" , "" )
if err != nil {
return err
}
defer os . Remove ( tempDotFile . Name ( ) )
// Next, we'll create (or re-create) the file that the final graph
// image will be written to.
2017-01-25 05:07:15 +03:00
imageFile , err := os . Create ( "graph.svg" )
2017-01-24 07:32:17 +03:00
if err != nil {
return err
}
// With our temporary files set up, we'll initialize the graphviz
// object that we'll use to draw our graph.
graphName := "LightningNetwork"
graphCanvas := gographviz . NewGraph ( )
graphCanvas . SetName ( graphName )
2017-01-25 05:07:15 +03:00
graphCanvas . SetDir ( false )
2017-01-24 07:32:17 +03:00
2017-01-26 05:27:27 +03:00
const numKeyChars = 10
truncateStr := func ( k string , n uint ) string {
return k [ : n ]
}
2017-01-24 07:32:17 +03:00
// For each node within the graph, we'll add a new vertex to the graph.
for _ , node := range graph . Nodes {
// Rather than using the entire hex-encoded string, we'll only
// use the first 10 characters. We also add a prefix of "Z" as
// graphviz is unable to parse the compressed pubkey as a
// non-integer.
//
// TODO(roasbeef): should be able to get around this?
2017-01-26 05:27:27 +03:00
nodeID := fmt . Sprintf ( ` "%v" ` , truncateStr ( node . PubKey , numKeyChars ) )
2017-01-24 07:32:17 +03:00
2017-12-03 05:42:12 +03:00
attrs := gographviz . Attrs { }
if node . Color != "" {
attrs [ "color" ] = fmt . Sprintf ( ` "%v" ` , node . Color )
}
graphCanvas . AddNode ( graphName , nodeID , attrs )
2017-01-24 07:32:17 +03:00
}
2017-01-25 05:07:15 +03:00
normalize := normalizeFunc ( graph . Edges , 3 )
2017-01-24 07:32:17 +03:00
// Similarly, for each edge we'll add an edge between the corresponding
// nodes added to the graph above.
for _ , edge := range graph . Edges {
// Once again, we add a 'Z' prefix so we're compliant with the
// dot grammar.
2017-01-26 05:27:27 +03:00
src := fmt . Sprintf ( ` "%v" ` , truncateStr ( edge . Node1Pub , numKeyChars ) )
dest := fmt . Sprintf ( ` "%v" ` , truncateStr ( edge . Node2Pub , numKeyChars ) )
2017-01-24 07:32:17 +03:00
// The weight for our edge will be the total capacity of the
// channel, in BTC.
2017-01-25 05:07:15 +03:00
// TODO(roasbeef): can also factor in the edges time-lock delta
// and fee information
2017-01-24 07:32:17 +03:00
amt := btcutil . Amount ( edge . Capacity ) . ToBTC ( )
edgeWeight := strconv . FormatFloat ( amt , 'f' , - 1 , 64 )
// The label for each edge will simply be a truncated version
2018-02-07 06:13:07 +03:00
// of its channel ID.
2017-01-26 05:27:27 +03:00
chanIDStr := strconv . FormatUint ( edge . ChannelId , 10 )
edgeLabel := fmt . Sprintf ( ` "cid:%v" ` , truncateStr ( chanIDStr , 7 ) )
2017-01-24 07:32:17 +03:00
2017-01-25 05:07:15 +03:00
// We'll also use a normalized version of the channels'
// capacity in satoshis in order to modulate the "thickness" of
// the line that creates the edge within the graph.
normalizedCapacity := normalize ( edge . Capacity )
edgeThickness := strconv . FormatFloat ( normalizedCapacity , 'f' , - 1 , 64 )
2017-12-03 05:42:31 +03:00
// If there's only a single channel in the graph, then we'll
// just set the edge thickness to 1 for everything.
if math . IsNaN ( normalizedCapacity ) {
edgeThickness = "1"
}
2017-01-26 05:27:27 +03:00
// TODO(roasbeef): color code based on percentile capacity
2017-01-25 05:07:15 +03:00
graphCanvas . AddEdge ( src , dest , false , gographviz . Attrs {
"penwidth" : edgeThickness ,
"weight" : edgeWeight ,
"label" : edgeLabel ,
} )
2017-01-24 07:32:17 +03:00
}
// With the declarative generation of the graph complete, we now write
// the dot-string description of the graph
graphDotString := graphCanvas . String ( )
if _ , err := tempDotFile . WriteString ( graphDotString ) ; err != nil {
return err
}
if err := tempDotFile . Sync ( ) ; err != nil {
return err
}
2017-01-26 05:29:24 +03:00
var errBuffer bytes . Buffer
2017-01-24 07:32:17 +03:00
// Once our dot file has been written to disk, we can use the dot
// command itself to generate the drawn rendering of the graph
// described.
2017-01-25 05:07:15 +03:00
drawCmd := exec . Command ( "dot" , "-T" + "svg" , "-o" + imageFile . Name ( ) ,
2017-01-24 07:32:17 +03:00
tempDotFile . Name ( ) )
2017-01-26 05:29:24 +03:00
drawCmd . Stderr = & errBuffer
2017-01-24 07:32:17 +03:00
if err := drawCmd . Run ( ) ; err != nil {
2017-01-26 05:29:24 +03:00
fmt . Println ( "error rendering graph: " , errBuffer . String ( ) )
fmt . Println ( "dot: " , graphDotString )
2017-01-24 07:32:17 +03:00
return err
}
2017-01-26 05:29:24 +03:00
errBuffer . Reset ( )
2017-01-24 07:32:17 +03:00
// Finally, we'll open the drawn graph to display to the user.
openCmd := exec . Command ( "open" , imageFile . Name ( ) )
2017-01-26 05:29:24 +03:00
openCmd . Stderr = & errBuffer
2017-01-24 07:32:17 +03:00
if err := openCmd . Run ( ) ; err != nil {
2017-01-26 05:29:24 +03:00
fmt . Println ( "error opening rendered graph image: " ,
errBuffer . String ( ) )
2017-01-24 07:32:17 +03:00
return err
}
return nil
}
2017-02-24 16:32:33 +03:00
var listPaymentsCommand = cli . Command {
2017-03-03 01:23:16 +03:00
Name : "listpayments" ,
2018-02-06 02:05:04 +03:00
Usage : "List all outgoing payments" ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( listPayments ) ,
2016-12-05 14:59:36 +03:00
}
func listPayments ( ctx * cli . Context ) error {
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-12-05 14:59:36 +03:00
req := & lnrpc . ListPaymentsRequest { }
payments , err := client . ListPayments ( context . Background ( ) , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( payments )
2016-12-28 02:45:10 +03:00
return nil
}
2017-02-24 16:32:33 +03:00
var getChanInfoCommand = cli . Command {
2016-12-28 02:45:10 +03:00
Name : "getchaninfo" ,
2018-02-06 02:05:04 +03:00
Usage : "Get the state of a channel" ,
Description : "Prints out the latest authenticated state for a " +
2016-12-28 02:45:10 +03:00
"particular channel" ,
2017-03-03 01:23:16 +03:00
ArgsUsage : "chan_id" ,
2016-12-28 02:45:10 +03:00
Flags : [ ] cli . Flag {
2017-03-03 01:23:16 +03:00
cli . Int64Flag {
2016-12-28 02:45:10 +03:00
Name : "chan_id" ,
Usage : "the 8-byte compact channel ID to query for" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( getChanInfo ) ,
2016-12-28 02:45:10 +03:00
}
func getChanInfo ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-12-28 02:45:10 +03:00
2017-03-03 01:23:16 +03:00
var (
2017-03-09 07:44:32 +03:00
chanID int64
err error
2017-03-03 01:23:16 +03:00
)
switch {
case ctx . IsSet ( "chan_id" ) :
2017-03-09 07:44:32 +03:00
chanID = ctx . Int64 ( "chan_id" )
2017-03-03 01:23:16 +03:00
case ctx . Args ( ) . Present ( ) :
2017-03-09 07:44:32 +03:00
chanID , err = strconv . ParseInt ( ctx . Args ( ) . First ( ) , 10 , 64 )
2017-03-03 01:23:16 +03:00
default :
return fmt . Errorf ( "chan_id argument missing" )
}
2016-12-28 02:45:10 +03:00
req := & lnrpc . ChanInfoRequest {
2017-03-09 07:44:32 +03:00
ChanId : uint64 ( chanID ) ,
2016-12-28 02:45:10 +03:00
}
chanInfo , err := client . GetChanInfo ( ctxb , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( chanInfo )
2016-12-28 02:45:10 +03:00
return nil
}
2017-02-24 16:32:33 +03:00
var getNodeInfoCommand = cli . Command {
2016-12-28 02:45:10 +03:00
Name : "getnodeinfo" ,
2017-03-03 01:23:16 +03:00
Usage : "Get information on a specific node." ,
2018-02-06 02:05:04 +03:00
Description : "Prints out the latest authenticated node state for an " +
2016-12-28 02:45:10 +03:00
"advertised node" ,
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "pub_key" ,
Usage : "the 33-byte hex-encoded compressed public of the target " +
"node" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( getNodeInfo ) ,
2016-12-28 02:45:10 +03:00
}
func getNodeInfo ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-12-28 02:45:10 +03:00
2017-04-13 21:55:17 +03:00
args := ctx . Args ( )
var pubKey string
switch {
case ctx . IsSet ( "pub_key" ) :
pubKey = ctx . String ( "pub_key" )
case args . Present ( ) :
pubKey = args . First ( )
default :
2017-03-03 01:23:16 +03:00
return fmt . Errorf ( "pub_key argument missing" )
}
2016-12-28 02:45:10 +03:00
req := & lnrpc . NodeInfoRequest {
2017-04-13 21:55:17 +03:00
PubKey : pubKey ,
2016-12-28 02:45:10 +03:00
}
nodeInfo , err := client . GetNodeInfo ( ctxb , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( nodeInfo )
2016-12-28 02:45:10 +03:00
return nil
}
2017-03-21 05:01:57 +03:00
var queryRoutesCommand = cli . Command {
Name : "queryroutes" ,
2017-03-03 01:23:16 +03:00
Usage : "Query a route to a destination." ,
Description : "Queries the channel router for a potential path to the destination that has sufficient flow for the amount including fees" ,
ArgsUsage : "dest amt" ,
2016-12-28 02:45:10 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "dest" ,
Usage : "the 33-byte hex-encoded public key for the payment " +
"destination" ,
} ,
2017-03-03 01:23:16 +03:00
cli . Int64Flag {
2016-12-28 02:45:10 +03:00
Name : "amt" ,
Usage : "the amount to send expressed in satoshis" ,
} ,
2018-02-13 03:29:34 +03:00
cli . Int64Flag {
Name : "num_max_routes" ,
Usage : "the max number of routes to be returned (default: 10)" ,
Value : 10 ,
} ,
2016-12-28 02:45:10 +03:00
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( queryRoutes ) ,
2016-12-28 02:45:10 +03:00
}
2017-03-21 05:01:57 +03:00
func queryRoutes ( ctx * cli . Context ) error {
2016-12-28 02:45:10 +03:00
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-12-28 02:45:10 +03:00
2017-03-03 01:23:16 +03:00
var (
dest string
amt int64
err error
)
args := ctx . Args ( )
switch {
case ctx . IsSet ( "dest" ) :
dest = ctx . String ( "dest" )
case args . Present ( ) :
dest = args . First ( )
args = args . Tail ( )
default :
return fmt . Errorf ( "dest argument missing" )
}
switch {
case ctx . IsSet ( "amt" ) :
amt = ctx . Int64 ( "amt" )
case args . Present ( ) :
amt , err = strconv . ParseInt ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode amt argument: %v" , err )
}
default :
return fmt . Errorf ( "amt argument missing" )
}
2017-03-21 05:01:57 +03:00
req := & lnrpc . QueryRoutesRequest {
2018-02-13 03:29:34 +03:00
PubKey : dest ,
Amt : amt ,
NumRoutes : int32 ( ctx . Int ( "num_max_routes" ) ) ,
2016-12-28 02:45:10 +03:00
}
2017-03-21 05:01:57 +03:00
route , err := client . QueryRoutes ( ctxb , req )
2016-12-28 02:45:10 +03:00
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( route )
2016-12-28 02:45:10 +03:00
return nil
}
2017-02-24 16:32:33 +03:00
var getNetworkInfoCommand = cli . Command {
2016-12-28 02:45:10 +03:00
Name : "getnetworkinfo" ,
2018-02-06 02:05:04 +03:00
Usage : "Getnetworkinfo" ,
Description : "Returns a set of statistics pertaining to the known channel " +
2016-12-28 02:45:10 +03:00
"graph" ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( getNetworkInfo ) ,
2016-12-28 02:45:10 +03:00
}
func getNetworkInfo ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2016-12-28 02:45:10 +03:00
req := & lnrpc . NetworkInfoRequest { }
netInfo , err := client . GetNetworkInfo ( ctxb , req )
if err != nil {
return err
}
2016-12-05 14:59:36 +03:00
2017-02-23 22:56:47 +03:00
printRespJSON ( netInfo )
2016-12-05 14:59:36 +03:00
return nil
2016-12-27 08:52:15 +03:00
}
2017-01-15 05:19:02 +03:00
2017-02-24 16:32:33 +03:00
var debugLevelCommand = cli . Command {
2017-11-23 22:40:14 +03:00
Name : "debuglevel" ,
Usage : "Set the debug level." ,
Description : ` Logging level for all subsystems { trace , debug , info , warn , error , critical }
You may also specify < subsystem >= < level > , < subsystem2 >= < level > , ... to set the log level for individual subsystems
Use show to list available subsystems ` ,
2017-01-15 05:19:02 +03:00
Flags : [ ] cli . Flag {
cli . BoolFlag {
Name : "show" ,
Usage : "if true, then the list of available sub-systems will be printed out" ,
} ,
cli . StringFlag {
Name : "level" ,
2017-04-13 21:55:17 +03:00
Usage : "the level specification to target either a coarse logging level, or granular set of specific sub-systems with logging levels for each" ,
2017-01-15 05:19:02 +03:00
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( debugLevel ) ,
2017-01-15 05:19:02 +03:00
}
func debugLevel ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2017-01-15 05:19:02 +03:00
req := & lnrpc . DebugLevelRequest {
Show : ctx . Bool ( "show" ) ,
LevelSpec : ctx . String ( "level" ) ,
}
resp , err := client . DebugLevel ( ctxb , req )
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( resp )
2017-01-15 05:19:02 +03:00
return nil
}
2017-01-18 00:39:30 +03:00
2018-02-07 06:11:11 +03:00
var decodePayReqCommand = cli . Command {
2017-01-18 00:39:30 +03:00
Name : "decodepayreq" ,
2017-03-03 01:23:16 +03:00
Usage : "Decode a payment request." ,
2017-01-18 00:39:30 +03:00
Description : "Decode the passed payment request revealing the destination, payment hash and value of the payment request" ,
2017-03-03 01:23:16 +03:00
ArgsUsage : "pay_req" ,
2017-01-18 00:39:30 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "pay_req" ,
2017-09-05 19:11:04 +03:00
Usage : "the bech32 encoded payment request" ,
2017-01-18 00:39:30 +03:00
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( decodePayReq ) ,
2017-01-18 00:39:30 +03:00
}
func decodePayReq ( ctx * cli . Context ) error {
ctxb := context . Background ( )
2017-01-30 01:51:30 +03:00
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
2017-01-18 00:39:30 +03:00
2017-03-03 01:23:16 +03:00
var payreq string
switch {
case ctx . IsSet ( "pay_req" ) :
payreq = ctx . String ( "pay_req" )
case ctx . Args ( ) . Present ( ) :
payreq = ctx . Args ( ) . First ( )
default :
return fmt . Errorf ( "pay_req argument missing" )
2017-01-18 00:39:30 +03:00
}
2017-01-30 01:56:31 +03:00
resp , err := client . DecodePayReq ( ctxb , & lnrpc . PayReqString {
2017-03-03 01:23:16 +03:00
PayReq : payreq ,
2017-01-30 01:56:31 +03:00
} )
2017-01-18 00:39:30 +03:00
if err != nil {
return err
}
2017-02-23 22:56:47 +03:00
printRespJSON ( resp )
2017-01-18 00:39:30 +03:00
return nil
}
2017-03-04 11:23:04 +03:00
2017-03-09 07:44:32 +03:00
var listChainTxnsCommand = cli . Command {
2017-03-04 11:23:04 +03:00
Name : "listchaintxns" ,
Usage : "List transactions from the wallet." ,
Description : "List all transactions an address of the wallet was involved in." ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( listChainTxns ) ,
2017-03-04 11:23:04 +03:00
}
func listChainTxns ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
resp , err := client . GetTransactions ( ctxb , & lnrpc . GetTransactionsRequest { } )
if err != nil {
return err
}
2017-03-09 07:44:32 +03:00
printRespJSON ( resp )
2017-03-04 11:23:04 +03:00
return nil
}
2017-05-12 00:55:56 +03:00
var stopCommand = cli . Command {
2017-11-23 22:40:14 +03:00
Name : "stop" ,
Usage : "Stop and shutdown the daemon." ,
Description : `
Gracefully stop all daemon subsystems before stopping the daemon itself .
This is equivalent to stopping it using CTRL - C . ` ,
Action : actionDecorator ( stopDaemon ) ,
2017-05-12 00:55:56 +03:00
}
func stopDaemon ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
_ , err := client . StopDaemon ( ctxb , & lnrpc . StopRequest { } )
if err != nil {
return err
}
return nil
}
2017-04-20 05:33:09 +03:00
var signMessageCommand = cli . Command {
Name : "signmessage" ,
2018-02-06 02:05:04 +03:00
Usage : "Sign a message with the node's private key" ,
2017-04-20 05:33:09 +03:00
ArgsUsage : "msg" ,
2017-11-23 22:40:14 +03:00
Description : `
Sign msg with the resident node ' s private key .
Returns the signature as a zbase32 string .
Positional arguments and flags can be used interchangeably but not at the same time ! ` ,
2017-04-20 05:33:09 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "msg" ,
Usage : "the message to sign" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( signMessage ) ,
2017-04-20 05:33:09 +03:00
}
func signMessage ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
var msg [ ] byte
switch {
case ctx . IsSet ( "msg" ) :
msg = [ ] byte ( ctx . String ( "msg" ) )
case ctx . Args ( ) . Present ( ) :
msg = [ ] byte ( ctx . Args ( ) . First ( ) )
default :
return fmt . Errorf ( "msg argument missing" )
}
resp , err := client . SignMessage ( ctxb , & lnrpc . SignMessageRequest { Msg : msg } )
if err != nil {
return err
}
printRespJSON ( resp )
return nil
}
var verifyMessageCommand = cli . Command {
Name : "verifymessage" ,
2018-02-06 02:05:04 +03:00
Usage : "Verify a message signed with the signature" ,
2017-04-20 05:33:09 +03:00
ArgsUsage : "msg signature" ,
2017-11-23 22:40:14 +03:00
Description : `
Verify that the message was signed with a properly - formed signature
The signature must be zbase32 encoded and signed with the private key of
an active node in the resident node ' s channel database .
Positional arguments and flags can be used interchangeably but not at the same time ! ` ,
2017-04-20 05:33:09 +03:00
Flags : [ ] cli . Flag {
cli . StringFlag {
Name : "msg" ,
Usage : "the message to verify" ,
} ,
cli . StringFlag {
2017-04-29 14:44:29 +03:00
Name : "sig" ,
2017-04-20 05:33:09 +03:00
Usage : "the zbase32 encoded signature of the message" ,
} ,
} ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( verifyMessage ) ,
2017-04-20 05:33:09 +03:00
}
func verifyMessage ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
var (
2017-04-29 14:44:29 +03:00
msg [ ] byte
sig string
2017-04-20 05:33:09 +03:00
)
args := ctx . Args ( )
switch {
case ctx . IsSet ( "msg" ) :
msg = [ ] byte ( ctx . String ( "msg" ) )
case args . Present ( ) :
msg = [ ] byte ( ctx . Args ( ) . First ( ) )
args = args . Tail ( )
default :
return fmt . Errorf ( "msg argument missing" )
}
switch {
2017-04-29 14:44:29 +03:00
case ctx . IsSet ( "sig" ) :
sig = ctx . String ( "sig" )
2017-04-20 05:33:09 +03:00
case args . Present ( ) :
2017-04-29 14:44:29 +03:00
sig = args . First ( )
2017-04-20 05:33:09 +03:00
default :
return fmt . Errorf ( "signature argument missing" )
}
2017-04-29 14:44:29 +03:00
req := & lnrpc . VerifyMessageRequest { Msg : msg , Signature : sig }
2017-04-20 05:33:09 +03:00
resp , err := client . VerifyMessage ( ctxb , req )
if err != nil {
return err
}
printRespJSON ( resp )
return nil
}
2017-08-22 10:29:08 +03:00
var feeReportCommand = cli . Command {
Name : "feereport" ,
2018-02-06 02:05:04 +03:00
Usage : "Display the current fee policies of all active channels" ,
2018-01-18 21:32:24 +03:00
Description : `
Returns the current fee policies of all active channels .
2017-12-17 01:13:17 +03:00
Fee policies can be updated using the updatechanpolicy command . ` ,
2017-11-07 01:34:49 +03:00
Action : actionDecorator ( feeReport ) ,
2017-08-22 10:29:08 +03:00
}
func feeReport ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
req := & lnrpc . FeeReportRequest { }
resp , err := client . FeeReport ( ctxb , req )
if err != nil {
return err
}
printRespJSON ( resp )
return nil
}
2017-12-17 01:13:17 +03:00
var updateChannelPolicyCommand = cli . Command {
Name : "updatechanpolicy" ,
2018-02-06 02:05:04 +03:00
Usage : "Update the channel policy for all channels, or a single channel" ,
2017-12-17 01:13:17 +03:00
ArgsUsage : "base_fee_msat fee_rate time_lock_delta [channel_point]" ,
2017-11-23 22:40:14 +03:00
Description : `
2017-12-17 01:13:17 +03:00
Updates the channel policy for all channels , or just a particular channel
identified by its channel point . The update will be committed , and
2017-11-23 22:40:14 +03:00
broadcast to the rest of the network within the next batch .
Channel points are encoded as : funding_txid : output_index ` ,
2017-08-22 10:29:08 +03:00
Flags : [ ] cli . Flag {
cli . Int64Flag {
Name : "base_fee_msat" ,
Usage : "the base fee in milli-satoshis that will " +
"be charged for each forwarded HTLC, regardless " +
"of payment size" ,
} ,
cli . StringFlag {
Name : "fee_rate" ,
Usage : "the fee rate that will be charged " +
"proportionally based on the value of each " +
"forwarded HTLC, the lowest possible rate is 0.000001" ,
} ,
2017-12-17 01:13:17 +03:00
cli . Int64Flag {
Name : "time_lock_delta" ,
Usage : "the CLTV delta that will be applied to all " +
"forwarded HTLCs" ,
} ,
2017-08-22 10:29:08 +03:00
cli . StringFlag {
Name : "chan_point" ,
Usage : "The channel whose fee policy should be " +
"updated, if nil the policies for all channels " +
"will be updated. Takes the form of: txid:output_index" ,
} ,
} ,
2017-12-17 01:13:17 +03:00
Action : actionDecorator ( updateChannelPolicy ) ,
2017-08-22 10:29:08 +03:00
}
2017-12-17 01:13:17 +03:00
func updateChannelPolicy ( ctx * cli . Context ) error {
2017-08-22 10:29:08 +03:00
ctxb := context . Background ( )
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
var (
2017-12-17 01:13:17 +03:00
baseFee int64
feeRate float64
timeLockDelta int64
err error
2017-08-22 10:29:08 +03:00
)
args := ctx . Args ( )
switch {
case ctx . IsSet ( "base_fee_msat" ) :
baseFee = ctx . Int64 ( "base_fee_msat" )
case args . Present ( ) :
baseFee , err = strconv . ParseInt ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode base_fee_msat: %v" , err )
}
args = args . Tail ( )
default :
return fmt . Errorf ( "base_fee_msat argument missing" )
}
switch {
case ctx . IsSet ( "fee_rate" ) :
feeRate = ctx . Float64 ( "fee_rate" )
case args . Present ( ) :
feeRate , err = strconv . ParseFloat ( args . First ( ) , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode fee_rate: %v" , err )
}
args = args . Tail ( )
default :
return fmt . Errorf ( "fee_rate argument missing" )
}
2017-12-17 01:13:17 +03:00
switch {
case ctx . IsSet ( "time_lock_delta" ) :
timeLockDelta = ctx . Int64 ( "time_lock_delta" )
case args . Present ( ) :
timeLockDelta , err = strconv . ParseInt ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode time_lock_delta: %v" ,
err )
}
args = args . Tail ( )
default :
return fmt . Errorf ( "time_lock_delta argument missing" )
}
2017-08-22 10:29:08 +03:00
var (
chanPoint * lnrpc . ChannelPoint
chanPointStr string
)
2017-12-17 01:13:17 +03:00
2017-08-22 10:29:08 +03:00
switch {
case ctx . IsSet ( "chan_point" ) :
chanPointStr = ctx . String ( "chan_point" )
case args . Present ( ) :
chanPointStr = args . First ( )
}
if chanPointStr != "" {
split := strings . Split ( chanPointStr , ":" )
if len ( split ) != 2 {
return fmt . Errorf ( "expecting chan_point to be in format of: " +
"txid:index" )
}
index , err := strconv . ParseInt ( split [ 1 ] , 10 , 32 )
if err != nil {
return fmt . Errorf ( "unable to decode output index: %v" , err )
}
chanPoint = & lnrpc . ChannelPoint {
2018-01-11 07:59:30 +03:00
FundingTxid : & lnrpc . ChannelPoint_FundingTxidStr {
FundingTxidStr : split [ 0 ] ,
} ,
2017-08-22 10:29:08 +03:00
OutputIndex : uint32 ( index ) ,
}
}
2017-12-17 01:13:17 +03:00
req := & lnrpc . PolicyUpdateRequest {
BaseFeeMsat : baseFee ,
FeeRate : feeRate ,
TimeLockDelta : uint32 ( timeLockDelta ) ,
2017-08-22 10:29:08 +03:00
}
if chanPoint != nil {
2017-12-17 01:13:17 +03:00
req . Scope = & lnrpc . PolicyUpdateRequest_ChanPoint {
2017-08-22 10:29:08 +03:00
ChanPoint : chanPoint ,
}
} else {
2017-12-17 01:13:17 +03:00
req . Scope = & lnrpc . PolicyUpdateRequest_Global {
2017-08-22 10:29:08 +03:00
Global : true ,
}
}
2017-12-17 01:13:17 +03:00
resp , err := client . UpdateChannelPolicy ( ctxb , req )
2017-08-22 10:29:08 +03:00
if err != nil {
return err
}
printRespJSON ( resp )
return nil
}
2018-02-28 09:24:37 +03:00
var forwardingHistoryCommand = cli . Command {
Name : "fwdinghistory" ,
Usage : "Query the history of all forwarded htlcs" ,
ArgsUsage : "start_time [end_time] [index_offset] [max_events]" ,
Description : `
Query the htlc switch ' s internal forwarding log for all completed
payment circuits ( HTLCs ) over a particular time range ( -- start_time and
-- end_time ) . The start and end times are meant to be expressed in
seconds since the Unix epoch . If a start and end time aren ' t provided ,
then events over the past 24 hours are queried for .
The max number of events returned is 50 k . The default number is 100 ,
callers can use the -- max_events param to modify this value .
Finally , callers can skip a series of events using the -- index_offset
parameter . Each response will contain the offset index of the last
entry . Using this callers can manually paginate within a time slice .
` ,
Flags : [ ] cli . Flag {
cli . Int64Flag {
Name : "start_time" ,
Usage : "the starting time for the query, expressed in " +
"seconds since the unix epoch" ,
} ,
cli . Int64Flag {
Name : "end_time" ,
Usage : "the end time for the query, expressed in " +
"seconds since the unix epoch" ,
} ,
cli . Int64Flag {
Name : "index_offset" ,
Usage : "the number of events to skip" ,
} ,
cli . Int64Flag {
Name : "max_events" ,
Usage : "the max number of events to return" ,
} ,
} ,
Action : actionDecorator ( forwardingHistory ) ,
}
func forwardingHistory ( ctx * cli . Context ) error {
ctxb := context . Background ( )
client , cleanUp := getClient ( ctx )
defer cleanUp ( )
var (
startTime , endTime uint64
indexOffset , maxEvents uint32
err error
)
args := ctx . Args ( )
switch {
case ctx . IsSet ( "start_time" ) :
startTime = ctx . Uint64 ( "start_time" )
case args . Present ( ) :
startTime , err = strconv . ParseUint ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode start_time %v" , err )
}
args = args . Tail ( )
}
switch {
case ctx . IsSet ( "end_time" ) :
endTime = ctx . Uint64 ( "end_time" )
case args . Present ( ) :
endTime , err = strconv . ParseUint ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode end_time: %v" , err )
}
args = args . Tail ( )
}
switch {
case ctx . IsSet ( "index_offset" ) :
indexOffset = uint32 ( ctx . Int64 ( "index_offset" ) )
case args . Present ( ) :
i , err := strconv . ParseInt ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode index_offset: %v" , err )
}
indexOffset = uint32 ( i )
args = args . Tail ( )
}
switch {
case ctx . IsSet ( "max_events" ) :
maxEvents = uint32 ( ctx . Int64 ( "max_events" ) )
case args . Present ( ) :
m , err := strconv . ParseInt ( args . First ( ) , 10 , 64 )
if err != nil {
return fmt . Errorf ( "unable to decode max_events: %v" , err )
}
maxEvents = uint32 ( m )
args = args . Tail ( )
}
req := & lnrpc . ForwardingHistoryRequest {
StartTime : startTime ,
EndTime : endTime ,
IndexOffset : indexOffset ,
NumMaxEvents : maxEvents ,
}
resp , err := client . ForwardingHistory ( ctxb , req )
if err != nil {
return err
}
printRespJSON ( resp )
return nil
}