This repository has been archived by the owner on Jun 25, 2024. It is now read-only.
forked from lightninglabs/pool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
order.go
722 lines (618 loc) · 18.9 KB
/
order.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
package clientdb
import (
"bytes"
"errors"
"fmt"
"io"
"github.com/btcsuite/btcutil"
"github.com/getvoltage/pool/event"
"github.com/getvoltage/pool/order"
"github.com/getvoltage/pool/sidecar"
"github.com/lightningnetwork/lnd/tlv"
"go.etcd.io/bbolt"
)
const (
// bidSelfChanBalanceType is the tlv type we use to store the self
// channel balance on bid orders.
bidSelfChanBalanceType tlv.Type = 1
// bidSidecarTicketType is the tlv type we use to store the sidecar
// ticket on bid orders.
bidSidecarTicketType tlv.Type = 2
)
var (
// ErrNoOrder is the error returned if no order with the given nonce
// exists in the store.
ErrNoOrder = errors.New("no order found")
// ErrOrderExists is returned if an order is submitted that is already
// known to the store.
ErrOrderExists = errors.New("order with this nonce already exists")
// ordersBucketKey is a bucket that contains all orders that are
// currently pending or completed. This bucket is keyed by the nonce and
// leads to a nested sub-bucket that houses information for that order.
ordersBucketKey = []byte("orders")
// orderKey is the key that stores the serialized order. It is nested
// within the sub-bucket for each active order.
//
// path: ordersBucketKey -> orderBucket[nonce] -> orderKey
orderKey = []byte("order")
// orderTierKey is a key within the order bucket for an order. It
// stores the min node tier for an order. It allows an order to specify
// the required minimum node tier for matching and execution.
orderTierKey = []byte("order-tier")
// orderMinUnitsMatchKey is the key that stores the serialized order's
// minimum units match. It is nested within the sub-bucket for each
// active order.
//
// path: ordersBucketKey -> orderBucket[nonce] -> orderMinUnitsMatchKey
orderMinUnitsMatchKey = []byte("order-min-units-match")
// orderTlvKey is a key within the order bucket for additional, tlv
// encoded data.
orderTlvKey = []byte("order-tlv")
)
type extraOrderData struct {
minNodeTier order.NodeTier
minUnitsMatch order.SupplyUnit
tlvData []byte
}
// orderCallback is a function type that is used to pass as a callback into the
// store's fetch functions to deliver the results to the caller. It also
// includes any auxiliary order information as additional arguments after the
// raw order bytes.
type orderCallback func(nonce order.Nonce, rawOrder []byte,
extraData *extraOrderData) error
// SubmitOrder stores an order by using the orders's nonce as an identifier. If
// an order with the given nonce already exists in the store, ErrOrderExists is
// returned.
//
// NOTE: This is part of the Store interface.
func (db *DB) SubmitOrder(newOrder order.Order) error {
return db.Update(func(tx *bbolt.Tx) error {
rootBucket, err := getBucket(tx, ordersBucketKey)
if err != nil {
return err
}
err = fetchOrderTX(rootBucket, newOrder.Nonce(), nil)
switch err {
// No error means there is an order with that nonce in the DB
// already.
case nil:
return ErrOrderExists
// This is what we want, no order with that nonce should be
// known.
case ErrNoOrder:
// Surface any other error.
default:
return err
}
// Serialize and store the order now that we know it doesn't
// exist yet.
var w bytes.Buffer
err = SerializeOrder(newOrder, &w)
if err != nil {
return err
}
// Create an event for the initial order and store it in the
// order's event bucket but also in the global events under an
// unique timestamp.
evt := NewCreatedEvent(newOrder)
err = storeOrderTX(
rootBucket, newOrder.Nonce(), w.Bytes(), evt,
)
if err != nil {
return err
}
err = storeOrderMinUnitsMatchTX(
rootBucket, newOrder.Nonce(),
newOrder.Details().MinUnitsMatch,
)
if err != nil {
return err
}
// Next, store any additional order data as a tlv stream.
if err := storeOrderTlvTX(
rootBucket, newOrder.Nonce(), newOrder,
); err != nil {
return err
}
// Finally, store the min node tier, but only if this is a Bid
// order.
if bidOrder, ok := newOrder.(*order.Bid); ok {
return storeOrderMinNoderTierTX(
rootBucket, newOrder.Nonce(),
bidOrder.MinNodeTier,
)
}
return nil
})
}
// UpdateOrder updates an order in the database according to the given
// modifiers.
//
// NOTE: This is part of the Store interface.
func (db *DB) UpdateOrder(nonce order.Nonce, modifiers ...order.Modifier) error {
return db.Update(func(tx *bbolt.Tx) error {
rootBucket, err := getBucket(tx, ordersBucketKey)
if err != nil {
return err
}
_, err = updateOrder(rootBucket, rootBucket, nonce, modifiers)
return err
})
}
// UpdateOrders atomically updates a list of orders in the database according to
// the given modifiers.
//
// NOTE: This is part of the Store interface.
func (db *DB) UpdateOrders(nonces []order.Nonce,
modifiers [][]order.Modifier) error {
if len(nonces) != len(modifiers) {
return fmt.Errorf("invalid number of modifiers")
}
// Read and update the orders in one single transaction that they are
// updated atomically.
return db.Update(func(tx *bbolt.Tx) error {
rootBucket, err := getBucket(tx, ordersBucketKey)
if err != nil {
return err
}
for idx, nonce := range nonces {
_, err := updateOrder(
rootBucket, rootBucket, nonce, modifiers[idx],
)
if err != nil {
return err
}
}
return nil
})
}
// GetOrder returns an order by looking up the nonce. If no order with that
// nonce exists in the store, ErrNoOrder is returned.
//
// NOTE: This is part of the Store interface.
func (db *DB) GetOrder(nonce order.Nonce) (order.Order, error) {
var (
o order.Order
err error
callback = func(nonce order.Nonce, rawOrder []byte,
extraData *extraOrderData) error {
r := bytes.NewReader(rawOrder)
o, err = DeserializeOrder(nonce, r)
if err != nil {
return err
}
tlvReader := bytes.NewReader(extraData.tlvData)
err = deserializeOrderTlvData(tlvReader, o)
if err != nil {
return err
}
// TODO(roasbeef): factory func to de-dup w/ all other
// instances?
if bidOrder, ok := o.(*order.Bid); ok {
bidOrder.MinNodeTier = extraData.minNodeTier
}
o.Details().MinUnitsMatch = extraData.minUnitsMatch
return nil
}
)
err = db.View(func(tx *bbolt.Tx) error {
rootBucket, err := getBucket(tx, ordersBucketKey)
if err != nil {
return err
}
return fetchOrderTX(rootBucket, nonce, callback)
})
return o, err
}
// GetOrders returns all orders that are currently known to the store.
//
// NOTE: This is part of the Store interface.
func (db *DB) GetOrders() ([]order.Order, error) {
var (
orders []order.Order
callback = func(nonce order.Nonce, rawOrder []byte,
extraData *extraOrderData) error {
r := bytes.NewReader(rawOrder)
o, err := DeserializeOrder(nonce, r)
if err != nil {
return err
}
tlvReader := bytes.NewReader(extraData.tlvData)
err = deserializeOrderTlvData(tlvReader, o)
if err != nil {
return err
}
if bidOrder, ok := o.(*order.Bid); ok {
bidOrder.MinNodeTier = extraData.minNodeTier
}
o.Details().MinUnitsMatch = extraData.minUnitsMatch
orders = append(orders, o)
return nil
}
)
err := db.View(func(tx *bbolt.Tx) error {
// First, we'll grab our main order bucket key.
rootBucket, err := getBucket(tx, ordersBucketKey)
if err != nil {
return err
}
// We'll now traverse the root bucket for all orders. The
// primary key is the order nonce itself.
return rootBucket.ForEach(func(nonceBytes, val []byte) error {
// Only go into things that we know are sub-bucket keys.
if val != nil {
return nil
}
// Get the order from the bucket and pass it to the
// caller.
var nonce order.Nonce
copy(nonce[:], nonceBytes)
return fetchOrderTX(rootBucket, nonce, callback)
})
})
if err != nil {
return nil, err
}
return orders, nil
}
// storeOrderTX saves a byte serialized order in its specific sub bucket within
// the root orders bucket.
func storeOrderTX(rootBucket *bbolt.Bucket, nonce order.Nonce,
orderBytes []byte, evt event.Event) error {
// From the root bucket, we'll make a new sub order bucket using
// the order nonce.
orderBucket, err := rootBucket.CreateBucketIfNotExists(nonce[:])
if err != nil {
return err
}
// Add the event to the global event store but also add a reference to
// it in the order bucket.
if err := storeEventTX(orderBucket, evt); err != nil {
return err
}
// With the order bucket created, we'll store the order itself.
return orderBucket.Put(orderKey, orderBytes)
}
// storeOrderMinNoderTierTX saves the current node tier for a given order to
// the proper bucket.
func storeOrderMinNoderTierTX(rootBucket *bbolt.Bucket, nonce order.Nonce,
minNodeTier order.NodeTier) error {
orderBucket, err := rootBucket.CreateBucketIfNotExists(nonce[:])
if err != nil {
return err
}
var b bytes.Buffer
if err := WriteElements(&b, minNodeTier); err != nil {
return err
}
return orderBucket.Put(orderTierKey, b.Bytes())
}
// storeOrderMinUnitsMatchTX saves the order's minimum units match within the
// order's root bucket.
func storeOrderMinUnitsMatchTX(rootBucket *bbolt.Bucket, nonce order.Nonce,
minUnitsMatch order.SupplyUnit) error {
// From the root bucket, we'll make a new sub order bucket using
// the order nonce.
orderBucket, err := rootBucket.CreateBucketIfNotExists(nonce[:])
if err != nil {
return err
}
// With the order bucket created, we'll store the order's min units
// match.
var buf bytes.Buffer
if err := WriteElement(&buf, minUnitsMatch); err != nil {
return err
}
return orderBucket.Put(orderMinUnitsMatchKey, buf.Bytes())
}
// storeOrderTlvTX saves the order's additional information as a tlv stream
// within the order's root bucket.
func storeOrderTlvTX(rootBucket *bbolt.Bucket, nonce order.Nonce,
o order.Order) error {
orderBucket, err := rootBucket.CreateBucketIfNotExists(nonce[:])
if err != nil {
return err
}
var b bytes.Buffer
if err := serializeOrderTlvData(&b, o); err != nil {
return err
}
return orderBucket.Put(orderTlvKey, b.Bytes())
}
// fetchOrderTX fetches the binary data of one order specified by its nonce from
// the root orders bucket.
func fetchOrderTX(rootBucket *bbolt.Bucket, nonce order.Nonce,
callback orderCallback) error {
// Get the main order bucket next.
orderBucket := rootBucket.Bucket(nonce[:])
if orderBucket == nil {
return ErrNoOrder
}
// With the main order bucket obtained, we'll grab the raw order
// bytes and pass them back to the caller.
orderBytes := orderBucket.Get(orderKey)
if orderBytes == nil {
return fmt.Errorf("order bucket not found")
}
if callback == nil {
return nil
}
// Try to read our extra order data. Use a default of 1 for the min
// units matched if the field does not exist (possible for older
// orders).
extraData := &extraOrderData{
minUnitsMatch: order.SupplyUnit(1),
tlvData: orderBucket.Get(orderTlvKey),
}
nodeTierBytes := orderBucket.Get(orderTierKey)
if nodeTierBytes != nil {
err := ReadElements(
bytes.NewReader(nodeTierBytes), &extraData.minNodeTier,
)
if err != nil {
return err
}
}
minUnitsMatchBytes := orderBucket.Get(orderMinUnitsMatchKey)
if minUnitsMatchBytes != nil {
err := ReadElements(
bytes.NewReader(minUnitsMatchBytes),
&extraData.minUnitsMatch,
)
if err != nil {
return err
}
}
return callback(nonce, orderBytes, extraData)
}
// updateOrder fetches the binary data of one order specified by its nonce from
// the orders bucket, applies the modifiers, and stores it back into dst bucket.
// The dst bucket can be a different bucket than the orders bucket if an order
// update should be written to a staging area instead of being applied to the
// original order directly. Do not use this function for applying the staged
// changes to the final bucket but use copyOrder instead.
func updateOrder(ordersBucket, dst *bbolt.Bucket, nonce order.Nonce,
modifiers []order.Modifier) (order.Order, error) {
var (
o order.Order
err error
callback = func(nonce order.Nonce, rawOrder []byte,
extraData *extraOrderData) error {
r := bytes.NewReader(rawOrder)
o, err = DeserializeOrder(nonce, r)
if err != nil {
return err
}
tlvReader := bytes.NewReader(extraData.tlvData)
err = deserializeOrderTlvData(tlvReader, o)
if err != nil {
return err
}
if bidOrder, ok := o.(*order.Bid); ok {
bidOrder.MinNodeTier = extraData.minNodeTier
}
o.Details().MinUnitsMatch = extraData.minUnitsMatch
return nil
}
)
// Retrieve the order stored in the database.
err = fetchOrderTX(ordersBucket, nonce, callback)
if err != nil {
return nil, err
}
// Preserve the original state to detect a state change later.
prevState := o.Details().State
// Apply the given modifications to it and store it back.
for _, modifier := range modifiers {
modifier(o.Details())
}
var w bytes.Buffer
err = SerializeOrder(o, &w)
if err != nil {
return nil, err
}
// Create an event for the update now. We always store the event
// reference to the order in the main order bucket, even if the
// destination bucket is the pending orders bucket.
evt := NewUpdatedEvent(prevState, o)
orderBucket := ordersBucket.Bucket(nonce[:])
if orderBucket == nil {
return nil, ErrNoOrder
}
// Add the event to the global event store but also add a reference to
// it in the order's event reference sub bucket.
if err := storeEventTX(orderBucket, evt); err != nil {
return nil, err
}
// Store the order to the destination bucket now, skipping the event as
// we've already written that to the source bucket.
if err := storeOrderTX(dst, nonce, w.Bytes(), nil); err != nil {
return nil, err
}
err = storeOrderMinUnitsMatchTX(dst, nonce, o.Details().MinUnitsMatch)
if err != nil {
return nil, err
}
// Next, store any additional order data as a tlv stream.
if err := storeOrderTlvTX(dst, nonce, o); err != nil {
return nil, err
}
if bidOrder, ok := o.(*order.Bid); ok {
err = storeOrderMinNoderTierTX(dst, nonce, bidOrder.MinNodeTier)
if err != nil {
return nil, err
}
}
return o, nil
}
// copyOrder copies a single order from the source to destination bucket. No
// event references are copied, only the order itself.
func copyOrder(src, dst *bbolt.Bucket, nonce order.Nonce) error {
var (
o order.Order
orderBytes []byte
nodeTier order.NodeTier
minUnitsMatch order.SupplyUnit
err error
callback = func(_ order.Nonce, rawOrder []byte,
extraData *extraOrderData) error {
orderBytes = rawOrder
// In order to know if we need the node tier at all,
// we'll go ahead and decode fully this order in
// question.
r := bytes.NewReader(rawOrder)
o, err = DeserializeOrder(nonce, r)
if err != nil {
return err
}
tlvReader := bytes.NewReader(extraData.tlvData)
err = deserializeOrderTlvData(tlvReader, o)
if err != nil {
return err
}
nodeTier = extraData.minNodeTier
minUnitsMatch = extraData.minUnitsMatch
return nil
}
)
// Retrieve the order stored in the source bucket.
err = fetchOrderTX(src, nonce, callback)
if err != nil {
return err
}
// Store it in the new bucket.
if err := storeOrderTX(dst, nonce, orderBytes, nil); err != nil {
return err
}
// Next, store any additional order data as a tlv stream.
if err := storeOrderTlvTX(dst, nonce, o); err != nil {
return err
}
if _, ok := o.(*order.Bid); ok {
err := storeOrderMinNoderTierTX(dst, nonce, nodeTier)
if err != nil {
return err
}
}
return storeOrderMinUnitsMatchTX(dst, nonce, minUnitsMatch)
}
// SerializeOrder binary serializes an order to a writer using the common LN
// wire format.
func SerializeOrder(o order.Order, w io.Writer) error {
kit := o.Details()
// We don't have to deserialize the nonce as it's the sub bucket name.
return WriteElements(
w, kit.Preimage, kit.Version, o.Type(), kit.State,
kit.FixedRate, kit.Amt, kit.Units, kit.MultiSigKeyLocator,
kit.MaxBatchFeeRate, kit.AcctKey, kit.UnitsUnfulfilled,
kit.LeaseDuration,
)
}
// DeserializeOrder deserializes an order from the binary LN wire format.
func DeserializeOrder(nonce order.Nonce, r io.Reader) (
order.Order, error) {
var (
kit = order.NewKit(nonce)
orderType order.Type
)
// We don't serialize the nonce as it's part of the bucket name already.
err := ReadElements(
r, &kit.Preimage, &kit.Version, &orderType, &kit.State,
&kit.FixedRate, &kit.Amt, &kit.Units, &kit.MultiSigKeyLocator,
&kit.MaxBatchFeeRate, &kit.AcctKey, &kit.UnitsUnfulfilled,
&kit.LeaseDuration,
)
if err != nil {
return nil, err
}
// Now read the order type specific fields.
switch orderType {
case order.TypeAsk:
return &order.Ask{
Kit: *kit,
}, nil
case order.TypeBid:
return &order.Bid{
Kit: *kit,
}, nil
default:
return nil, fmt.Errorf("unknown order type: %d", orderType)
}
}
// deserializeOrderTlvData attempts to decode the remaining bytes in the
// supplied reader by interpreting it as a tlv stream. If successful any
// non-default values of the additional data will be set on the given order.
func deserializeOrderTlvData(r io.Reader, o order.Order) error {
var (
selfChanBalance uint64
sidecarTicket []byte
)
// We'll add records for all possible additional order data fields here
// but will check below which of them were actually set, depending on
// the order type as well.
tlvStream, err := tlv.NewStream(
tlv.MakePrimitiveRecord(
bidSelfChanBalanceType, &selfChanBalance,
),
tlv.MakePrimitiveRecord(bidSidecarTicketType, &sidecarTicket),
)
if err != nil {
return err
}
parsedTypes, err := tlvStream.DecodeWithParsedTypes(r)
if err != nil {
return err
}
// Now check what records were actually parsed from the stream and
// assign any parsed fields to our order.
switch castOrder := o.(type) {
case *order.Ask:
case *order.Bid:
if t, ok := parsedTypes[bidSelfChanBalanceType]; ok && t == nil {
castOrder.SelfChanBalance = btcutil.Amount(
selfChanBalance,
)
}
if t, ok := parsedTypes[bidSidecarTicketType]; ok && t == nil {
castOrder.SidecarTicket, err = sidecar.DeserializeTicket(
bytes.NewReader(sidecarTicket),
)
if err != nil {
return err
}
}
}
return nil
}
// serializeOrderTlvData encodes all additional data of an order as a single tlv
// stream.
func serializeOrderTlvData(w io.Writer, o order.Order) error {
var tlvRecords []tlv.Record
switch castOrder := o.(type) {
case *order.Ask:
case *order.Bid:
if castOrder.SelfChanBalance != 0 {
selfChanBalance := uint64(castOrder.SelfChanBalance)
tlvRecords = append(tlvRecords, tlv.MakePrimitiveRecord(
bidSelfChanBalanceType, &selfChanBalance,
))
}
if castOrder.SidecarTicket != nil {
var buf bytes.Buffer
if err := sidecar.SerializeTicket(
&buf, castOrder.SidecarTicket,
); err != nil {
return err
}
sidecarBytes := buf.Bytes()
tlvRecords = append(tlvRecords, tlv.MakePrimitiveRecord(
bidSidecarTicketType, &sidecarBytes,
))
}
}
tlvStream, err := tlv.NewStream(tlvRecords...)
if err != nil {
return err
}
return tlvStream.Encode(w)
}