|
| 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