Skip to content

Commit 52dbc03

Browse files
committed
lndclient: add NewBasicClient function
1 parent f1f72bb commit 52dbc03

File tree

2 files changed

+72
-1
lines changed

2 files changed

+72
-1
lines changed

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,5 @@ require (
1515
golang.org/x/net v0.0.0-20190313220215-9f648a60d977
1616
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19
1717
google.golang.org/grpc v1.19.0
18-
gopkg.in/macaroon.v2 v2.1.0 // indirect
18+
gopkg.in/macaroon.v2 v2.1.0
1919
)

lndclient/basic_client.go

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package lndclient
2+
3+
import (
4+
"fmt"
5+
"io/ioutil"
6+
"path/filepath"
7+
8+
"github.com/lightningnetwork/lnd/lncfg"
9+
"github.com/lightningnetwork/lnd/lnrpc"
10+
"github.com/lightningnetwork/lnd/macaroons"
11+
"google.golang.org/grpc"
12+
"google.golang.org/grpc/credentials"
13+
macaroon "gopkg.in/macaroon.v2"
14+
)
15+
16+
// NewBasicClient creates a new basic gRPC client to lnd. We call this client
17+
// "basic" as it uses a global macaroon (by default the admin macaroon) for the
18+
// entire connection, and falls back to expected defaults if the arguments
19+
// aren't provided.
20+
func NewBasicClient(lndHost, tlsPath, macPath, network string) (lnrpc.LightningClient, error) {
21+
if tlsPath == "" {
22+
tlsPath = defaultTLSCertPath
23+
}
24+
25+
// Load the specified TLS certificate and build transport credentials
26+
creds, err := credentials.NewClientTLSFromFile(tlsPath, "")
27+
if err != nil {
28+
return nil, err
29+
}
30+
31+
// Create a dial options array.
32+
opts := []grpc.DialOption{
33+
grpc.WithTransportCredentials(creds),
34+
}
35+
36+
if macPath == "" {
37+
macPath = filepath.Join(
38+
defaultLndDir, defaultDataDir, defaultChainSubDir,
39+
"bitcoin", network, defaultAdminMacaroonFilename,
40+
)
41+
}
42+
43+
// Load the specified macaroon file.
44+
macBytes, err := ioutil.ReadFile(macPath)
45+
if err == nil {
46+
// Only if file is found
47+
mac := &macaroon.Macaroon{}
48+
if err = mac.UnmarshalBinary(macBytes); err != nil {
49+
return nil, fmt.Errorf("unable to decode macaroon: %v",
50+
err)
51+
}
52+
53+
// Now we append the macaroon credentials to the dial options.
54+
cred := macaroons.NewMacaroonCredential(mac)
55+
opts = append(opts, grpc.WithPerRPCCredentials(cred))
56+
}
57+
58+
// We need to use a custom dialer so we can also connect to unix sockets
59+
// and not just TCP addresses.
60+
opts = append(
61+
opts, grpc.WithDialer(
62+
lncfg.ClientAddressDialer(defaultRPCPort),
63+
),
64+
)
65+
conn, err := grpc.Dial(lndHost, opts...)
66+
if err != nil {
67+
return nil, fmt.Errorf("unable to connect to RPC server: %v", err)
68+
}
69+
70+
return lnrpc.NewLightningClient(conn), nil
71+
}

0 commit comments

Comments
 (0)