forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 24
/
invoices_server.go
437 lines (365 loc) · 12.5 KB
/
invoices_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//go:build !no_invoicesrpc
// +build !no_invoicesrpc
package invoicesrpc
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"gopkg.in/macaroon-bakery.v2/bakery"
"github.com/decred/dcrlnd/channeldb"
"github.com/decred/dcrlnd/lnrpc"
"github.com/decred/dcrlnd/lntypes"
"github.com/decred/dcrlnd/macaroons"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)
const (
// subServerName is the name of the sub rpc server. We'll use this name
// to register ourselves, and we also require that the main
// SubServerConfigDispatcher instance recognize it as the name of our
// RPC service.
subServerName = "InvoicesRPC"
)
var (
// macaroonOps are the set of capabilities that our minted macaroon (if
// it doesn't already exist) will have.
macaroonOps = []bakery.Op{
{
Entity: "invoices",
Action: "write",
},
{
Entity: "invoices",
Action: "read",
},
}
// macPermissions maps RPC calls to the permissions they require.
macPermissions = map[string][]bakery.Op{
"/invoicesrpc.Invoices/SubscribeSingleInvoice": {{
Entity: "invoices",
Action: "read",
}},
"/invoicesrpc.Invoices/SettleInvoice": {{
Entity: "invoices",
Action: "write",
}},
"/invoicesrpc.Invoices/CancelInvoice": {{
Entity: "invoices",
Action: "write",
}},
"/invoicesrpc.Invoices/AddHoldInvoice": {{
Entity: "invoices",
Action: "write",
}},
"/invoicesrpc.Invoices/LookupInvoiceV2": {{
Entity: "invoices",
Action: "write",
}},
}
// DefaultInvoicesMacFilename is the default name of the invoices
// macaroon that we expect to find via a file handle within the main
// configuration file in this package.
DefaultInvoicesMacFilename = "invoices.macaroon"
)
// ServerShell is a shell struct holding a reference to the actual sub-server.
// It is used to register the gRPC sub-server with the root server before we
// have the necessary dependencies to populate the actual sub-server.
type ServerShell struct {
InvoicesServer
}
// Server is a sub-server of the main RPC server: the invoices RPC. This sub
// RPC server allows external callers to access the status of the invoices
// currently active within lnd, as well as configuring it at runtime.
type Server struct {
quit chan struct{}
cfg *Config
}
// A compile time check to ensure that Server fully implements the
// InvoicesServer gRPC service.
var _ InvoicesServer = (*Server)(nil)
// New returns a new instance of the invoicesrpc Invoices sub-server. We also
// return the set of permissions for the macaroons that we may create within
// this method. If the macaroons we need aren't found in the filepath, then
// we'll create them on start up. If we're unable to locate, or create the
// macaroons we need, then we'll return with an error.
func New(cfg *Config) (*Server, lnrpc.MacaroonPerms, error) {
// If the path of the invoices macaroon wasn't specified, then we'll
// assume that it's found at the default network directory.
macFilePath := filepath.Join(
cfg.NetworkDir, DefaultInvoicesMacFilename,
)
// Now that we know the full path of the invoices macaroon, we can
// check to see if we need to create it or not. If stateless_init is set
// then we don't write the macaroons.
if cfg.MacService != nil && !cfg.MacService.StatelessInit &&
!lnrpc.FileExists(macFilePath) {
log.Infof("Baking macaroons for invoices RPC Server at: %v",
macFilePath)
// At this point, we know that the invoices macaroon doesn't
// yet, exist, so we need to create it with the help of the
// main macaroon service.
invoicesMac, err := cfg.MacService.NewMacaroon(
context.Background(), macaroons.DefaultRootKeyID,
macaroonOps...,
)
if err != nil {
return nil, nil, err
}
invoicesMacBytes, err := invoicesMac.M().MarshalBinary()
if err != nil {
return nil, nil, err
}
err = ioutil.WriteFile(macFilePath, invoicesMacBytes, 0644)
if err != nil {
_ = os.Remove(macFilePath)
return nil, nil, err
}
}
server := &Server{
cfg: cfg,
quit: make(chan struct{}, 1),
}
return server, macPermissions, nil
}
// Start launches any helper goroutines required for the Server to function.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (s *Server) Start() error {
return nil
}
// Stop signals any active goroutines for a graceful closure.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (s *Server) Stop() error {
close(s.quit)
return nil
}
// Name returns a unique string representation of the sub-server. This can be
// used to identify the sub-server and also de-duplicate them.
//
// NOTE: This is part of the lnrpc.SubServer interface.
func (s *Server) Name() string {
return subServerName
}
// RegisterWithRootServer will be called by the root gRPC server to direct a sub
// RPC server to register itself with the main gRPC root server. Until this is
// called, each sub-server won't be able to have requests routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) RegisterWithRootServer(grpcServer *grpc.Server) error {
// We make sure that we register it with the main gRPC server to ensure
// all our methods are routed properly.
RegisterInvoicesServer(grpcServer, r)
log.Debugf("Invoices RPC server successfully registered with root " +
"gRPC server")
return nil
}
// RegisterWithRestServer will be called by the root REST mux to direct a sub
// RPC server to register itself with the main REST mux server. Until this is
// called, each sub-server won't be able to have requests routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) RegisterWithRestServer(ctx context.Context,
mux *runtime.ServeMux, dest string, opts []grpc.DialOption) error {
// We make sure that we register it with the main REST server to ensure
// all our methods are routed properly.
err := RegisterInvoicesHandlerFromEndpoint(ctx, mux, dest, opts)
if err != nil {
log.Errorf("Could not register Invoices REST server "+
"with root REST server: %v", err)
return err
}
log.Debugf("Invoices REST server successfully registered with " +
"root REST server")
return nil
}
// CreateSubServer populates the subserver's dependencies using the passed
// SubServerConfigDispatcher. This method should fully initialize the
// sub-server instance, making it ready for action. It returns the macaroon
// permissions that the sub-server wishes to pass on to the root server for all
// methods routed towards it.
//
// NOTE: This is part of the lnrpc.GrpcHandler interface.
func (r *ServerShell) CreateSubServer(configRegistry lnrpc.SubServerConfigDispatcher) (
lnrpc.SubServer, lnrpc.MacaroonPerms, error) {
subServer, macPermissions, err := createNewSubServer(configRegistry)
if err != nil {
return nil, nil, err
}
r.InvoicesServer = subServer
return subServer, macPermissions, nil
}
// SubscribeSingleInvoice returns a uni-directional stream (server -> client)
// for notifying the client of state changes for a specified invoice.
func (s *Server) SubscribeSingleInvoice(req *SubscribeSingleInvoiceRequest,
updateStream Invoices_SubscribeSingleInvoiceServer) error {
hash, err := lntypes.MakeHash(req.RHash)
if err != nil {
return err
}
invoiceClient, err := s.cfg.InvoiceRegistry.SubscribeSingleInvoice(hash)
if err != nil {
return err
}
defer invoiceClient.Cancel()
for {
select {
case newInvoice := <-invoiceClient.Updates:
rpcInvoice, err := CreateRPCInvoice(
newInvoice, s.cfg.ChainParams,
)
if err != nil {
return err
}
if err := updateStream.Send(rpcInvoice); err != nil {
return err
}
// If we have reached a terminal state, close the
// stream with no error.
if newInvoice.State.IsFinal() {
return nil
}
case <-updateStream.Context().Done():
return updateStream.Context().Err()
case <-s.quit:
return nil
}
}
}
// SettleInvoice settles an accepted invoice. If the invoice is already settled,
// this call will succeed.
func (s *Server) SettleInvoice(ctx context.Context,
in *SettleInvoiceMsg) (*SettleInvoiceResp, error) {
preimage, err := lntypes.MakePreimage(in.Preimage)
if err != nil {
return nil, err
}
err = s.cfg.InvoiceRegistry.SettleHodlInvoice(preimage)
if err != nil && err != channeldb.ErrInvoiceAlreadySettled {
return nil, err
}
return &SettleInvoiceResp{}, nil
}
// CancelInvoice cancels a currently open invoice. If the invoice is already
// canceled, this call will succeed. If the invoice is already settled, it will
// fail.
func (s *Server) CancelInvoice(ctx context.Context,
in *CancelInvoiceMsg) (*CancelInvoiceResp, error) {
paymentHash, err := lntypes.MakeHash(in.PaymentHash)
if err != nil {
return nil, err
}
err = s.cfg.InvoiceRegistry.CancelInvoice(paymentHash)
if err != nil {
return nil, err
}
log.Infof("Canceled invoice %v", paymentHash)
return &CancelInvoiceResp{}, nil
}
// AddHoldInvoice attempts to add a new hold invoice to the invoice database.
// Any duplicated invoices are rejected, therefore all invoices *must* have a
// unique payment hash.
func (s *Server) AddHoldInvoice(ctx context.Context,
invoice *AddHoldInvoiceRequest) (*AddHoldInvoiceResp, error) {
addInvoiceCfg := &AddInvoiceConfig{
AddInvoice: s.cfg.InvoiceRegistry.AddInvoice,
IsChannelActive: s.cfg.IsChannelActive,
ChainParams: s.cfg.ChainParams,
NodeSigner: s.cfg.NodeSigner,
DefaultCLTVExpiry: s.cfg.DefaultCLTVExpiry,
ChanDB: s.cfg.ChanStateDB,
Graph: s.cfg.GraphDB,
GenInvoiceFeatures: s.cfg.GenInvoiceFeatures,
GenAmpInvoiceFeatures: s.cfg.GenAmpInvoiceFeatures,
}
hash, err := lntypes.MakeHash(invoice.Hash)
if err != nil {
return nil, err
}
value, err := lnrpc.UnmarshallAmt(invoice.Value, invoice.ValueMAtoms)
if err != nil {
return nil, err
}
// Convert the passed routing hints to the required format.
routeHints, err := CreateZpay32HopHints(invoice.RouteHints)
if err != nil {
return nil, err
}
addInvoiceData := &AddInvoiceData{
Memo: invoice.Memo,
Hash: &hash,
Value: value,
DescriptionHash: invoice.DescriptionHash,
Expiry: invoice.Expiry,
FallbackAddr: invoice.FallbackAddr,
CltvExpiry: invoice.CltvExpiry,
Private: invoice.Private,
HodlInvoice: true,
Preimage: nil,
RouteHints: routeHints,
}
_, dbInvoice, err := AddInvoice(ctx, addInvoiceCfg, addInvoiceData)
if err != nil {
return nil, err
}
return &AddHoldInvoiceResp{
AddIndex: dbInvoice.AddIndex,
PaymentRequest: string(dbInvoice.PaymentRequest),
PaymentAddr: dbInvoice.Terms.PaymentAddr[:],
}, nil
}
// LookupInvoiceV2 attempts to look up at invoice. An invoice can be referenced
// using either its payment hash, payment address, or set ID.
func (s *Server) LookupInvoiceV2(ctx context.Context,
req *LookupInvoiceMsg) (*lnrpc.Invoice, error) {
var invoiceRef channeldb.InvoiceRef
// First, we'll attempt to parse out the invoice ref from the proto
// oneof. If none of the three currently supported types was
// specified, then we'll exit with an error.
switch {
case req.GetPaymentHash() != nil:
payHash, err := lntypes.MakeHash(req.GetPaymentHash())
if err != nil {
return nil, status.Error(
codes.InvalidArgument,
fmt.Sprintf("unable to parse pay hash: %v", err),
)
}
invoiceRef = channeldb.InvoiceRefByHash(payHash)
case req.GetPaymentAddr() != nil &&
req.LookupModifier == LookupModifier_HTLC_SET_BLANK:
var payAddr [32]byte
copy(payAddr[:], req.GetPaymentAddr())
invoiceRef = channeldb.InvoiceRefByAddrBlankHtlc(payAddr)
case req.GetPaymentAddr() != nil:
var payAddr [32]byte
copy(payAddr[:], req.GetPaymentAddr())
invoiceRef = channeldb.InvoiceRefByAddr(payAddr)
case req.GetSetId() != nil &&
req.LookupModifier == LookupModifier_HTLC_SET_ONLY:
var setID [32]byte
copy(setID[:], req.GetSetId())
invoiceRef = channeldb.InvoiceRefBySetIDFiltered(setID)
case req.GetSetId() != nil:
var setID [32]byte
copy(setID[:], req.GetSetId())
invoiceRef = channeldb.InvoiceRefBySetID(setID)
default:
return nil, status.Error(codes.InvalidArgument,
"invoice ref must be set")
}
// Attempt to locate the invoice, returning a nice "not found" error if
// we can't find it in the database.
invoice, err := s.cfg.InvoiceRegistry.LookupInvoiceByRef(invoiceRef)
switch {
case err == channeldb.ErrInvoiceNotFound:
return nil, status.Error(codes.NotFound, err.Error())
case err != nil:
return nil, err
}
return CreateRPCInvoice(&invoice, s.cfg.ChainParams)
}