forked from mit-dci/lit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lndb.go
711 lines (602 loc) · 17.1 KB
/
lndb.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
package qln
import (
"fmt"
"sync"
"github.com/adiabat/btcd/btcec"
"github.com/adiabat/btcd/wire"
"github.com/adiabat/btcutil"
"github.com/boltdb/bolt"
"github.com/mit-dci/lit/elkrem"
"github.com/mit-dci/lit/lndc"
"github.com/mit-dci/lit/lnutil"
"github.com/mit-dci/lit/watchtower"
)
/*
Channels (& multisig) go in the DB here.
first there's the peer bucket.
Here's the structure:
Channels
|
|-channelID (36 byte outpoint)
|
|- portxo data (includes peer id, channel ID)
|
|- Watchtower: watchtower data
|
|- State: state data
Peers
|
|- peerID (33 byte pubkey)
|
|- index (4 bytes)
|
|- hostname...?
|
|- channels..?
PeerMap
|
|-peerIdx(4) : peerPubkey(33)
ChannelMap
|
|-chanIdx(4) : channelID (36 byte outpoint)
Right now these buckets are all in one boltDB. This limits it to one db write
at a time, which for super high thoughput could be too slow.
Later on we can chop it up so that each channel gets it's own db file.
MultiWallit:
One LitNode can have a bunch of SubWallets. This is useful if you want to
have both testnet3 and regtest channels active simultaneously.
The SubWallet is a map of uint32s to Uwallet interfaces. The identifier for the
channel is the coin's HDCoinType, which is available from the params.
I said regtest is 257 because it's not defined in a BIP, and set to 1
(collision w/ testnet3) in the btcsuite code.
Other coins could use SLIP-44, which will be IPV4 all over again as people
make millions of pointless altcoins to grab that address space.
Since usually there is only 1 wallit connected, there is a DefaultWallet
which functions can use if the wallet is not specified. The first wallet
to get attached to DefaultWallet. There is also a bool MultiWallet which is
false while there is only 1 wallet, and true once there are more than one
wallets connected.
You can't remove wallets once they're attached; just restart instead.
*/
// LnNode is the main struct for the node, keeping track of all channel state and
// communicating with the underlying UWallet
type LitNode struct {
LitDB *bolt.DB // place to write all this down
LitFolder string // path to save stuff
IdentityKey *btcec.PrivateKey
// all nodes have a watchtower. but could have a tower without a node
Tower watchtower.Watcher
// BaseWallet is the underlying wallet which keeps track of utxos, secrets,
// and network i/o
// map of cointypes to wallets
SubWallet map[uint32]UWallet
// indicates if multiple wallets are connected
MultiWallet bool
// cointype of the first (possibly only) wallet connected
DefaultCoin uint32
RemoteCons map[uint32]*RemotePeer
RemoteMtx sync.Mutex
// WatchCon is currently just for the watchtower
WatchCon *lndc.LNDConn // merge these later
// OmniChan is the channel for the OmniHandler
OmniIn chan lnutil.LitMsg
OmniOut chan lnutil.LitMsg
// the current channel that in the process of being created
// (1 at a time for now)
InProg *InFlightFund
// Nodes don't have Params; their SubWallets do
// Param *chaincfg.Params // network parameters (testnet3, segnet, etc)
// queue for async messages to RPC user
UserMessageBox chan string
// The port(s) in which it listens for incoming connections
LisIpPorts []string
// The URL from which lit attempts to resolve the LN address
TrackerURL string
}
type RemotePeer struct {
Idx uint32 // the peer index
Nickname string
Con *lndc.LNDConn
QCs map[uint32]*Qchan // keep map of all peer's channels in ram
OpMap map[[36]byte]uint32 // quick lookup for channels
}
// InFlightFund is a funding transaction that has not yet been broadcast
type InFlightFund struct {
PeerIdx, ChanIdx, Coin uint32
Amt, InitSend int64
op *wire.OutPoint
done chan uint32
// use this to avoid crashiness
mtx sync.Mutex
}
func (inff *InFlightFund) Clear() {
inff.PeerIdx = 0
inff.ChanIdx = 0
inff.Amt = 0
inff.InitSend = 0
}
// GetPubHostFromPeerIdx gets the pubkey and internet host name for a peer
func (nd *LitNode) GetPubHostFromPeerIdx(idx uint32) ([33]byte, string) {
var pub [33]byte
var host string
// look up peer in db
err := nd.LitDB.View(func(btx *bolt.Tx) error {
mp := btx.Bucket(BKTPeerMap)
if mp == nil {
return nil
}
pubBytes := mp.Get(lnutil.U32tB(idx))
if pubBytes != nil {
copy(pub[:], pubBytes)
}
peerBkt := btx.Bucket(BKTPeers)
if peerBkt == nil {
return fmt.Errorf("no Peers")
}
prBkt := peerBkt.Bucket(pubBytes)
if prBkt == nil {
return fmt.Errorf("no peer %x", pubBytes)
}
host = string(prBkt.Get(KEYhost))
return nil
})
if err != nil {
fmt.Printf(err.Error())
}
return pub, host
}
// GetNicknameFromPeerIdx gets the nickname for a peer
func (nd *LitNode) GetNicknameFromPeerIdx(idx uint32) string {
var nickname string
// look up peer in db
err := nd.LitDB.View(func(btx *bolt.Tx) error {
mp := btx.Bucket(BKTPeerMap)
if mp == nil {
return nil
}
pubBytes := mp.Get(lnutil.U32tB(idx))
peerBkt := btx.Bucket(BKTPeers)
if peerBkt == nil {
return fmt.Errorf("no Peers")
}
prBkt := peerBkt.Bucket(pubBytes)
if prBkt == nil {
return fmt.Errorf("no peer %x", pubBytes)
}
nickname = string(prBkt.Get(KEYnickname))
return nil
})
if err != nil {
fmt.Printf(err.Error())
}
return nickname
}
// NextIdx returns the next channel index to use.
func (nd *LitNode) NextChannelIdx() (uint32, error) {
var cIdx uint32
err := nd.LitDB.View(func(btx *bolt.Tx) error {
cmp := btx.Bucket(BKTChanMap)
if cmp == nil {
return fmt.Errorf("NextIdxForPeer: no ChanMap")
}
cIdx = uint32(cmp.Stats().KeyN + 1)
return nil
})
if err != nil {
return 0, err
}
return cIdx, nil
}
// GetPeerIdx returns the peer index given a pubkey. Creates it if it's not there
// yet! Also return a bool for new..? not needed?
func (nd *LitNode) GetPeerIdx(pub *btcec.PublicKey, host string) (uint32, error) {
var idx uint32
err := nd.LitDB.Update(func(btx *bolt.Tx) error {
prs := btx.Bucket(BKTPeers) // only errs on name
thisPeerBkt := prs.Bucket(pub.SerializeCompressed())
// peer is already registered, return index without altering db.
if thisPeerBkt != nil {
idx = lnutil.BtU32(thisPeerBkt.Get(KEYIdx))
return nil
}
// this peer doesn't exist yet. Add new peer
mp := btx.Bucket(BKTPeerMap)
idx = uint32(mp.Stats().KeyN + 1)
// add index : pubkey into mapping
err := mp.Put(lnutil.U32tB(idx), pub.SerializeCompressed())
if err != nil {
return err
}
thisPeerBkt, err = prs.CreateBucket(pub.SerializeCompressed())
if err != nil {
return err
}
// save peer index in peer bucket
err = thisPeerBkt.Put(KEYIdx, lnutil.U32tB(idx))
if err != nil {
return err
}
// save remote host name (if it's there)
if host != "" {
err = thisPeerBkt.Put(KEYhost, []byte(host))
if err != nil {
return err
}
}
return nil
})
return idx, err
}
// SaveNicknameForPeerIdx saves/overwrites a nickname for a given peer idx
func (nd *LitNode) SaveNicknameForPeerIdx(nickname string, idx uint32) error {
var err error
// look up peer in db
err = nd.LitDB.Update(func(btx *bolt.Tx) error {
mp := btx.Bucket(BKTPeerMap)
if mp == nil {
return nil
}
pubBytes := mp.Get(lnutil.U32tB(idx))
peerBkt := btx.Bucket(BKTPeers)
if peerBkt == nil {
return fmt.Errorf("no Peers")
}
prBkt := peerBkt.Bucket(pubBytes)
if prBkt == nil {
return fmt.Errorf("no peer %x", pubBytes)
}
err = prBkt.Put(KEYnickname, []byte(nickname))
if err != nil {
return err
}
return nil
})
return err
}
// SaveQchanUtxoData saves utxo data such as outpoint and close tx / status
func (nd *LitNode) SaveQchanUtxoData(q *Qchan) error {
return nd.LitDB.Update(func(btx *bolt.Tx) error {
cbk := btx.Bucket(BKTChannel)
if cbk == nil {
return fmt.Errorf("no peers")
}
opArr := lnutil.OutPointToBytes(q.Op)
qcBucket := cbk.Bucket(opArr[:])
if qcBucket == nil {
return fmt.Errorf("outpoint %s not in db ", q.Op.String())
}
if q.CloseData.Closed {
closeBytes, err := q.CloseData.ToBytes()
if err != nil {
return err
}
err = qcBucket.Put(KEYqclose, closeBytes)
if err != nil {
return err
}
}
// serialize channel
qcBytes, err := q.ToBytes()
if err != nil {
return err
}
// save qchannel
return qcBucket.Put(KEYutxo, qcBytes)
})
}
// register a new Qchan in the db
func (nd *LitNode) SaveQChan(q *Qchan) error {
if q == nil {
return fmt.Errorf("SaveQChan: nil qchan")
}
// save channel to db. It has no state, and has no outpoint yet
err := nd.LitDB.Update(func(btx *bolt.Tx) error {
qOPArr := lnutil.OutPointToBytes(q.Op)
// make mapping of index to outpoint
cmp := btx.Bucket(BKTChanMap)
if cmp == nil {
return fmt.Errorf("SaveQChan: no channel map bucket")
}
// save index : outpoint
err := cmp.Put(lnutil.U32tB(q.Idx()), qOPArr[:])
if err != nil {
return err
}
fmt.Printf("saved %d : %s mapping in db\n", q.Idx(), q.Op.String())
cbk := btx.Bucket(BKTChannel) // go into bucket for all peers
if cbk == nil {
return fmt.Errorf("SaveQChan: no channel bucket")
}
// make bucket for this channel
qcBucket, err := cbk.CreateBucket(qOPArr[:])
if qcBucket == nil {
return fmt.Errorf("SaveQChan: can't make channel bucket")
}
// serialize channel
qcBytes, err := q.ToBytes()
if err != nil {
return err
}
// save qchannel in the bucket
err = qcBucket.Put(KEYutxo, qcBytes)
if err != nil {
return err
}
// also save all state; maybe there isn't any ..?
// serialize elkrem receiver if it exists
if q.ElkRcv != nil {
fmt.Printf("--- elk rcv exists, saving\n")
eb, err := q.ElkRcv.ToBytes()
if err != nil {
return err
}
// save elkrem
err = qcBucket.Put(KEYElkRecv, eb)
if err != nil {
return err
}
}
// serialize state
b, err := q.State.ToBytes()
if err != nil {
return err
}
// save state
fmt.Printf("writing %d byte state to bucket\n", len(b))
return qcBucket.Put(KEYState, b)
})
if err != nil {
return err
}
return nil
}
// RestoreQchanFromBucket loads the full qchan into memory from the
// bucket where it's stored. Loads the channel info, the elkrems,
// and the current state.
// restore happens all at once, but saving to the db can happen
// incrementally (updating states)
// This should populate everything int he Qchan struct: the elkrems and the states.
// Elkrem sender always works; is derived from local key data.
// Elkrem receiver can be "empty" with nothing in it (no data in db)
func (nd *LitNode) RestoreQchanFromBucket(bkt *bolt.Bucket) (*Qchan, error) {
if bkt == nil { // can't do anything without a bucket
return nil, fmt.Errorf("empty qchan bucket ")
}
// load the serialized channel base description
qc, err := QchanFromBytes(bkt.Get(KEYutxo))
if err != nil {
return nil, err
}
qc.CloseData, err = QCloseFromBytes(bkt.Get(KEYqclose))
if err != nil {
return nil, err
}
// get my channel pubkey
qc.MyPub, _ = nd.GetUsePub(qc.KeyGen, UseChannelFund)
// derive my refund / base point from index
qc.MyRefundPub, _ = nd.GetUsePub(qc.KeyGen, UseChannelRefund)
qc.MyHAKDBase, _ = nd.GetUsePub(qc.KeyGen, UseChannelHAKDBase)
// derive my watchtower refund PKH
watchRefundPub, _ := nd.GetUsePub(qc.KeyGen, UseChannelWatchRefund)
watchRefundPKHslice := btcutil.Hash160(watchRefundPub[:])
copy(qc.WatchRefundAdr[:], watchRefundPKHslice)
qc.State = new(StatCom)
// load state. If it exists.
// if it doesn't, leave as empty state, will fill in
stBytes := bkt.Get(KEYState)
if stBytes != nil {
qc.State, err = StatComFromBytes(stBytes)
if err != nil {
return nil, err
}
}
// load elkrem from elkrem bucket.
// shouldn't error even if nil. So shouldn't error, ever. Right?
// ignore error?
qc.ElkRcv, err = elkrem.ElkremReceiverFromBytes(bkt.Get(KEYElkRecv))
if err != nil {
return nil, err
}
if qc.ElkRcv != nil {
// fmt.Printf("loaded elkrem receiver at state %d\n", qc.ElkRcv.UpTo())
}
// derive elkrem sender root from HD keychain
r, _ := nd.GetElkremRoot(qc.KeyGen)
// set sender
qc.ElkSnd = elkrem.NewElkremSender(r)
// make the clear to send chan
qc.ClearToSend = make(chan bool, 1)
// set it to true (all qchannels start as clear to send in ram
// maybe they shouldn't be...?
qc.ClearToSend <- true
return &qc, nil
}
// ReloadQchan loads updated data from the db into the qchan. Loads elkrem
// and state, but does not change qchan info itself. Faster than GetQchan()
// also reload the channel close state
func (nd *LitNode) ReloadQchanState(q *Qchan) error {
var err error
opArr := lnutil.OutPointToBytes(q.Op)
return nd.LitDB.View(func(btx *bolt.Tx) error {
cbk := btx.Bucket(BKTChannel)
if cbk == nil {
return fmt.Errorf("no channels")
}
qcBucket := cbk.Bucket(opArr[:])
if qcBucket == nil {
return fmt.Errorf("outpoint %s not in db", q.Op.String())
}
// load state and update
// if it doesn't, leave as empty state, will fill in
stBytes := qcBucket.Get(KEYState)
if stBytes == nil {
return fmt.Errorf("state value empty")
}
q.State, err = StatComFromBytes(stBytes)
if err != nil {
return err
}
q.CloseData, err = QCloseFromBytes(qcBucket.Get(KEYqclose))
if err != nil {
return err
}
// load elkrem from elkrem bucket.
q.ElkRcv, err = elkrem.ElkremReceiverFromBytes(qcBucket.Get(KEYElkRecv))
if err != nil {
return err
}
return nil
})
}
// SetQchanRefund overwrites "theirrefund" and "theirHAKDbase" in a qchan.
// This is needed after getting a chanACK.
func (nd *LitNode) SetQchanRefund(q *Qchan, refund, hakdBase [33]byte) error {
return nd.LitDB.Update(func(btx *bolt.Tx) error {
cbk := btx.Bucket(BKTChannel)
if cbk == nil {
return fmt.Errorf("no channels")
}
opArr := lnutil.OutPointToBytes(q.Op)
qcBucket := cbk.Bucket(opArr[:])
if qcBucket == nil {
return fmt.Errorf("outpoint %s not in db ", q.Op.String())
}
// load the serialized channel base description
qc, err := QchanFromBytes(qcBucket.Get(KEYutxo))
if err != nil {
return err
}
// modify their refund
qc.TheirRefundPub = refund
// modify their HAKDbase
qc.TheirHAKDBase = hakdBase
// re -serialize
qcBytes, err := qc.ToBytes()
if err != nil {
return err
}
// save/overwrite
return qcBucket.Put(KEYutxo, qcBytes)
})
}
// Save / overwrite state of qChan in db
// the descent into the qchan bucket is boilerplate and it'd be nice
// if we can make that it's own function. Get channel bucket maybe? But then
// you have to close it...
func (nd *LitNode) SaveQchanState(q *Qchan) error {
return nd.LitDB.Update(func(btx *bolt.Tx) error {
cbk := btx.Bucket(BKTChannel)
if cbk == nil {
return fmt.Errorf("no channels")
}
opArr := lnutil.OutPointToBytes(q.Op)
qcBucket := cbk.Bucket(opArr[:])
if qcBucket == nil {
return fmt.Errorf("outpoint %s not in db ", q.Op.String())
}
// serialize elkrem receiver
eb, err := q.ElkRcv.ToBytes()
if err != nil {
return err
}
// save elkrem
err = qcBucket.Put(KEYElkRecv, eb)
if err != nil {
return err
}
// serialize state
b, err := q.State.ToBytes()
if err != nil {
return err
}
// save state
fmt.Printf("writing %d byte state to bucket\n", len(b))
return qcBucket.Put(KEYState, b)
})
}
// GetAllQchans returns a slice of all channels. empty slice is OK.
func (nd *LitNode) GetAllQchans() ([]*Qchan, error) {
var qChans []*Qchan
err := nd.LitDB.View(func(btx *bolt.Tx) error {
cbk := btx.Bucket(BKTChannel)
if cbk == nil {
return fmt.Errorf("no channels")
}
return cbk.ForEach(func(op, nothin []byte) error {
if nothin != nil {
return nil // non-bucket
}
qcBucket := cbk.Bucket(op)
if qcBucket == nil {
return nil // nothing stored
}
newQc, err := nd.RestoreQchanFromBucket(qcBucket)
if err != nil {
return err
}
// add to slice
qChans = append(qChans, newQc)
return nil
})
})
if err != nil {
return nil, err
}
return qChans, nil
}
// GetQchan returns a single channel.
// pubkey and outpoint bytes.
func (nd *LitNode) GetQchan(opArr [36]byte) (*Qchan, error) {
qc := new(Qchan)
var err error
op := lnutil.OutPointFromBytes(opArr)
err = nd.LitDB.View(func(btx *bolt.Tx) error {
cbk := btx.Bucket(BKTChannel)
if cbk == nil {
return fmt.Errorf("no channels")
}
qcBucket := cbk.Bucket(opArr[:])
if qcBucket == nil {
return fmt.Errorf("outpoint %s not in db", op.String())
}
qc, err = nd.RestoreQchanFromBucket(qcBucket)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return qc, nil
}
func (nd *LitNode) GetQchanOPfromIdx(cIdx uint32) ([36]byte, error) {
var rOp [36]byte
err := nd.LitDB.View(func(btx *bolt.Tx) error {
cmp := btx.Bucket(BKTChanMap)
if cmp == nil {
return fmt.Errorf("no channel map")
}
op := cmp.Get(lnutil.U32tB(cIdx))
if op == nil {
return fmt.Errorf("no channel %d in db", cIdx)
}
copy(rOp[:], op)
return nil
})
return rOp, err
}
// GetQchanByIdx is a gets the channel when you don't know the peer bytes and
// outpoint. Probably shouldn't have to use this if the UI is done right though.
func (nd *LitNode) GetQchanByIdx(cIdx uint32) (*Qchan, error) {
op, err := nd.GetQchanOPfromIdx(cIdx)
if err != nil {
return nil, err
}
fmt.Printf("got op %x\n", op)
qc, err := nd.GetQchan(op)
if err != nil {
return nil, err
}
return qc, nil
}