forked from cruzbit/cruzbit
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpeer.go
1684 lines (1482 loc) · 49.3 KB
/
peer.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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 cruzbit developers
// Use of this source code is governed by a MIT-style license that can be found in the LICENSE file.
package cruzbit
import (
"context"
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"net/url"
"sync"
"time"
"unicode/utf8"
"github.com/gorilla/websocket"
"github.com/seiflotfy/cuckoofilter"
"golang.org/x/crypto/ed25519"
)
// Peer is a peer client in the network. They all speak WebSocket protocol to each other.
// Peers could be fully validating and mining nodes or simply wallets.
type Peer struct {
conn *websocket.Conn
genesisID BlockID
peerStore PeerStorage
blockStore BlockStorage
ledger Ledger
processor *Processor
txQueue TransactionQueue
outbound bool
localDownloadQueue *BlockQueue // peer-local download queue
localInflightQueue *BlockQueue // peer-local inflight queue
globalInflightQueue *BlockQueue // global inflight queue
ignoreBlocks map[BlockID]bool
continuationBlockID BlockID
lastPeerAddressesReceivedTime time.Time
filterLock sync.RWMutex
filter *cuckoo.Filter
addrChan chan<- string
workID int32
workBlock *Block
medianTimestamp int64
pubKeys []ed25519.PublicKey
memo string
readLimitLock sync.RWMutex
readLimit int64
closeHandler func()
wg sync.WaitGroup
}
// PeerUpgrader upgrades the incoming HTTP connection to a WebSocket if the subprotocol matches.
var PeerUpgrader = websocket.Upgrader{
Subprotocols: []string{Protocol},
CheckOrigin: func(r *http.Request) bool { return true },
}
// NewPeer returns a new instance of a peer.
func NewPeer(conn *websocket.Conn, genesisID BlockID, peerStore PeerStorage,
blockStore BlockStorage, ledger Ledger, processor *Processor,
txQueue TransactionQueue, blockQueue *BlockQueue, addrChan chan<- string) *Peer {
peer := &Peer{
conn: conn,
genesisID: genesisID,
peerStore: peerStore,
blockStore: blockStore,
ledger: ledger,
processor: processor,
txQueue: txQueue,
localDownloadQueue: NewBlockQueue(),
localInflightQueue: NewBlockQueue(),
globalInflightQueue: blockQueue,
ignoreBlocks: make(map[BlockID]bool),
addrChan: addrChan,
}
peer.updateReadLimit()
return peer
}
// peerDialer is the websocket.Dialer to use for outbound peer connections
var peerDialer *websocket.Dialer = &websocket.Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 15 * time.Second,
Subprotocols: []string{Protocol}, // set in protocol.go
TLSClientConfig: tlsClientConfig, // set in tls.go
}
// Connect connects outbound to a peer.
func (p *Peer) Connect(ctx context.Context, addr, nonce, myAddr string) (int, error) {
u := url.URL{Scheme: "wss", Host: addr, Path: "/" + p.genesisID.String()}
log.Printf("Connecting to %s", u.String())
if err := p.peerStore.OnConnectAttempt(addr); err != nil {
return 0, err
}
header := http.Header{}
header.Add("Cruzbit-Peer-Nonce", nonce)
if len(myAddr) != 0 {
header.Add("Cruzbit-Peer-Address", myAddr)
}
// specify timeout via context. if the parent context is cancelled
// we'll also abort the connection.
dialCtx, cancel := context.WithTimeout(ctx, connectWait)
defer cancel()
var statusCode int
conn, resp, err := peerDialer.DialContext(dialCtx, u.String(), header)
if resp != nil {
statusCode = resp.StatusCode
}
if err != nil {
if statusCode == http.StatusTooManyRequests {
// the peer is already connected to us inbound.
// mark it successful so we try it again in the future.
p.peerStore.OnConnectSuccess(addr)
p.peerStore.OnDisconnect(addr)
} else {
p.peerStore.OnConnectFailure(addr)
}
return statusCode, err
}
p.conn = conn
p.outbound = true
return statusCode, p.peerStore.OnConnectSuccess(addr)
}
// OnClose specifies a handler to call when the peer connection is closed.
func (p *Peer) OnClose(closeHandler func()) {
p.closeHandler = closeHandler
}
// Shutdown is called to shutdown the underlying WebSocket synchronously.
func (p *Peer) Shutdown() {
var addr string
if p.conn != nil {
addr = p.conn.RemoteAddr().String()
p.conn.Close()
}
p.wg.Wait()
if len(addr) != 0 {
log.Printf("Closed connection with %s\n", addr)
}
}
const (
// Time allowed to wait for WebSocket connection
connectWait = 10 * time.Second
// Time allowed to write a message to the peer
writeWait = 30 * time.Second
// Time allowed to read the next pong message from the peer
pongWait = 120 * time.Second
// Send pings to peer with this period. Must be less than pongWait
pingPeriod = pongWait / 2
// How often should we refresh this peer's connectivity status with storage
peerStoreRefreshPeriod = 5 * time.Minute
// How often should we request peer addresses from a peer
getPeerAddressesPeriod = 1 * time.Hour
// Time allowed between processing new blocks before we consider a blockchain sync stalled
syncWait = 2 * time.Minute
// Maximum blocks per inv_block message
maxBlocksPerInv = 500
// Maximum local inflight queue size
inflightQueueMax = 8
// Maximum local download queue size
downloadQueueMax = maxBlocksPerInv * 10
)
// Run executes the peer's main loop in its own goroutine.
// It manages reading and writing to the peer's WebSocket and facilitating the protocol.
func (p *Peer) Run() {
p.wg.Add(1)
go p.run()
}
func (p *Peer) run() {
defer p.wg.Done()
if p.closeHandler != nil {
defer p.closeHandler()
}
peerAddr := p.conn.RemoteAddr().String()
defer func() {
// remove any inflight blocks this peer is no longer going to download
blockInflight, ok := p.localInflightQueue.Peek()
for ok {
p.localInflightQueue.Remove(blockInflight, "")
p.globalInflightQueue.Remove(blockInflight, peerAddr)
blockInflight, ok = p.localInflightQueue.Peek()
}
}()
defer p.conn.Close()
// written to by the reader loop to send outgoing messages to the writer loop
outChan := make(chan Message, 1)
// signals that the reader loop is exiting
defer close(outChan)
// send a find common ancestor request and request peer addresses shortly after connecting
onConnectChan := make(chan bool, 1)
go func() {
time.Sleep(5 * time.Second)
onConnectChan <- true
}()
// written to by the reader loop to update the current work block for the peer
getWorkChan := make(chan GetWorkMessage, 1)
submitWorkChan := make(chan SubmitWorkMessage, 1)
// writer goroutine loop
p.wg.Add(1)
go func() {
defer p.wg.Done()
// register to hear about tip block changes
tipChangeChan := make(chan TipChange, 10)
p.processor.RegisterForTipChange(tipChangeChan)
defer p.processor.UnregisterForTipChange(tipChangeChan)
// register to hear about new transactions
newTxChan := make(chan NewTx, MaxTransactionsToIncludePerBlock)
p.processor.RegisterForNewTransactions(newTxChan)
defer p.processor.UnregisterForNewTransactions(newTxChan)
// send the peer pings
tickerPing := time.NewTicker(pingPeriod)
defer tickerPing.Stop()
// update the peer store with the peer's connectivity
tickerPeerStoreRefresh := time.NewTicker(peerStoreRefreshPeriod)
defer tickerPeerStoreRefresh.Stop()
// request new peer addresses
tickerGetPeerAddresses := time.NewTicker(getPeerAddressesPeriod)
defer tickerGetPeerAddresses.Stop()
// check to see if we need to update work for miners
tickerUpdateWorkCheck := time.NewTicker(30 * time.Second)
defer tickerUpdateWorkCheck.Stop()
// update the peer store on disconnection
if p.outbound {
defer p.peerStore.OnDisconnect(peerAddr)
}
for {
select {
case m, ok := <-outChan:
if !ok {
// reader loop is exiting
return
}
// send outgoing message to peer
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := p.conn.WriteJSON(m); err != nil {
log.Printf("Write error: %s, to: %s\n", err, p.conn.RemoteAddr())
p.conn.Close()
}
case tip := <-tipChangeChan:
// update read limit if necessary
p.updateReadLimit()
if tip.Connect && tip.More == false {
// only build off newly connected tip blocks.
// create and send out new work if necessary
p.createNewWorkBlock(tip.BlockID, tip.Block.Header)
}
if tip.Source == p.conn.RemoteAddr().String() {
// this is who sent us the block that caused the change
break
}
if tip.Connect {
// new tip announced, notify the peer
inv := Message{
Type: "inv_block",
Body: InvBlockMessage{
BlockIDs: []BlockID{tip.BlockID},
},
}
// send it
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := p.conn.WriteJSON(inv); err != nil {
log.Printf("Write error: %s, to: %s\n", err, p.conn.RemoteAddr())
p.conn.Close()
}
}
// potentially create a filter_block
fb, err := p.createFilterBlock(tip.BlockID, tip.Block)
if err != nil {
log.Printf("Error: %s, to: %s\n", err, p.conn.RemoteAddr())
continue
}
if fb == nil {
continue
}
// send it
m := Message{
Type: "filter_block",
Body: fb,
}
if !tip.Connect {
m.Type = "filter_block_undo"
}
log.Printf("Sending %s with %d transaction(s), to: %s\n",
m.Type, len(fb.Transactions), p.conn.RemoteAddr())
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := p.conn.WriteJSON(m); err != nil {
log.Printf("Write error: %s, to: %s\n", err, p.conn.RemoteAddr())
p.conn.Close()
}
case newTx := <-newTxChan:
if newTx.Source == p.conn.RemoteAddr().String() {
// this is who sent it to us
break
}
interested := func() bool {
p.filterLock.RLock()
defer p.filterLock.RUnlock()
return p.filterLookup(newTx.Transaction)
}()
if !interested {
continue
}
// newly verified transaction announced, relay to peer
pushTx := Message{
Type: "push_transaction",
Body: PushTransactionMessage{
Transaction: newTx.Transaction,
},
}
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := p.conn.WriteJSON(pushTx); err != nil {
log.Printf("Write error: %s, to: %s\n", err, p.conn.RemoteAddr())
p.conn.Close()
}
case <-onConnectChan:
// send a new peer a request to find a common ancestor
if err := p.sendFindCommonAncestor(nil, true, outChan); err != nil {
log.Printf("Write error: %s, to: %s\n", err, p.conn.RemoteAddr())
p.conn.Close()
}
// send a get_peer_addresses to request peers
log.Printf("Sending get_peer_addresses to: %s\n", p.conn.RemoteAddr())
m := Message{Type: "get_peer_addresses"}
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := p.conn.WriteJSON(m); err != nil {
log.Printf("Error sending get_peer_addresses: %s, to: %s\n", err, p.conn.RemoteAddr())
p.conn.Close()
}
case gw := <-getWorkChan:
p.onGetWork(gw)
case sw := <-submitWorkChan:
p.onSubmitWork(sw)
case <-tickerPing.C:
//log.Printf("Sending ping message to: %s\n", p.conn.RemoteAddr())
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := p.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
log.Printf("Write error: %s, to: %s\n", err, p.conn.RemoteAddr())
p.conn.Close()
}
case <-tickerPeerStoreRefresh.C:
if p.outbound == false {
break
}
// periodically refresh our connection time
if err := p.peerStore.OnConnectSuccess(p.conn.RemoteAddr().String()); err != nil {
log.Printf("Error from peer store: %s\n", err)
}
case <-tickerGetPeerAddresses.C:
// periodically send a get_peer_addresses
log.Printf("Sending get_peer_addresses to: %s\n", p.conn.RemoteAddr())
m := Message{Type: "get_peer_addresses"}
p.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := p.conn.WriteJSON(m); err != nil {
log.Printf("Error sending get_peer_addresses: %s, to: %s\n", err, p.conn.RemoteAddr())
p.conn.Close()
}
case <-tickerUpdateWorkCheck.C:
if p.workBlock == nil {
// peer doesn't have work
break
}
txCount := len(p.workBlock.Transactions)
if txCount == MaxTransactionsToIncludePerBlock {
// already at capacity
break
}
if txCount-1 != p.txQueue.Len() {
tipID, tipHeader, _, err := getChainTipHeader(p.ledger, p.blockStore)
if err != nil {
log.Printf("Error reading chain tip header: %s\n", err)
break
}
p.createNewWorkBlock(*tipID, tipHeader)
}
}
}
}()
// are we syncing?
lastNewBlockTime := time.Now()
ibd, _, err := IsInitialBlockDownload(p.ledger, p.blockStore)
if err != nil {
log.Println(err)
return
}
// handle pongs
p.conn.SetPongHandler(func(string) error {
if ibd {
// handle stalled blockchain syncs
var err error
ibd, _, err = IsInitialBlockDownload(p.ledger, p.blockStore)
if err != nil {
return err
}
if ibd && time.Since(lastNewBlockTime) > syncWait {
return fmt.Errorf("Sync has stalled, disconnecting")
}
} else {
// try processing the queue in case we've been blocked by another client
// and their attempt has now expired
if err := p.processDownloadQueue(outChan); err != nil {
return err
}
}
p.conn.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
// set initial read deadline
p.conn.SetReadDeadline(time.Now().Add(pongWait))
// reader loop
for {
// update read limit
p.conn.SetReadLimit(p.getReadLimit())
// new message from peer
messageType, message, err := p.conn.ReadMessage()
if err != nil {
log.Printf("Read error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
switch messageType {
case websocket.TextMessage:
// sanitize inputs
if !utf8.Valid(message) {
log.Printf("Peer sent us non-utf8 clean message, from: %s\n", p.conn.RemoteAddr())
return
}
var body json.RawMessage
m := Message{Body: &body}
if err := json.Unmarshal([]byte(message), &m); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
// hangup if the peer is sending oversized messages
if m.Type != "block" && len(message) > MaxProtocolMessageLength {
log.Printf("Received too large (%d bytes) of a '%s' message, from: %s",
len(message), m.Type, p.conn.RemoteAddr())
return
}
switch m.Type {
case "inv_block":
var inv InvBlockMessage
if err := json.Unmarshal(body, &inv); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
for i, id := range inv.BlockIDs {
if err := p.onInvBlock(id, i, len(inv.BlockIDs), outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
}
case "get_block":
var gb GetBlockMessage
if err := json.Unmarshal(body, &gb); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onGetBlock(gb.BlockID, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "get_block_by_height":
var gbbh GetBlockByHeightMessage
if err := json.Unmarshal(body, &gbbh); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onGetBlockByHeight(gbbh.Height, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "block":
var b BlockMessage
if err := json.Unmarshal(body, &b); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if b.Block == nil {
log.Printf("Error: received nil block, from: %s\n", p.conn.RemoteAddr())
return
}
if b.Block.Header == nil {
log.Printf("Error: received nil block header, from: %s\n", p.conn.RemoteAddr())
return
}
ok, err := p.onBlock(b.Block, ibd, outChan)
if err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
if ok {
lastNewBlockTime = time.Now()
}
case "find_common_ancestor":
var fca FindCommonAncestorMessage
if err := json.Unmarshal(body, &fca); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
num := len(fca.BlockIDs)
for i, id := range fca.BlockIDs {
ok, err := p.onFindCommonAncestor(id, i, num, outChan)
if err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
if ok {
// don't need to process more
break
}
}
case "get_block_header":
var gbh GetBlockHeaderMessage
if err := json.Unmarshal(body, &gbh); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onGetBlockHeader(gbh.BlockID, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "get_block_header_by_height":
var gbhbh GetBlockHeaderByHeightMessage
if err := json.Unmarshal(body, &gbhbh); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onGetBlockHeaderByHeight(gbhbh.Height, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "get_balance":
var gb GetBalanceMessage
if err := json.Unmarshal(body, &gb); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onGetBalance(gb.PublicKey, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "get_balances":
var gb GetBalancesMessage
if err := json.Unmarshal(body, &gb); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onGetBalances(gb.PublicKeys, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "get_public_key_transactions":
var gpkt GetPublicKeyTransactionsMessage
if err := json.Unmarshal(body, &gpkt); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onGetPublicKeyTransactions(gpkt.PublicKey,
gpkt.StartHeight, gpkt.EndHeight, gpkt.StartIndex, gpkt.Limit, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "get_transaction":
var gt GetTransactionMessage
if err := json.Unmarshal(body, >); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onGetTransaction(gt.TransactionID, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "get_tip_header":
if err := p.onGetTipHeader(outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "push_transaction":
var pt PushTransactionMessage
if err := json.Unmarshal(body, &pt); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if pt.Transaction == nil {
log.Printf("Error: received nil transaction, from: %s\n", p.conn.RemoteAddr())
return
}
if err := p.onPushTransaction(pt.Transaction, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "push_transaction_result":
var ptr PushTransactionResultMessage
if err := json.Unmarshal(body, &ptr); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if len(ptr.Error) != 0 {
log.Printf("Error: %s, from: %s\n", ptr.Error, p.conn.RemoteAddr())
}
case "filter_load":
var fl FilterLoadMessage
if err := json.Unmarshal(body, &fl); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onFilterLoad(fl.Type, fl.Filter, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "filter_add":
var fa FilterAddMessage
if err := json.Unmarshal(body, &fa); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if err := p.onFilterAdd(fa.PublicKeys, outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "get_filter_transaction_queue":
p.onGetFilterTransactionQueue(outChan)
case "get_peer_addresses":
if err := p.onGetPeerAddresses(outChan); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
break
}
case "peer_addresses":
var pa PeerAddressesMessage
if err := json.Unmarshal(body, &pa); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
p.onPeerAddresses(pa.Addresses)
case "get_transaction_relay_policy":
outChan <- Message{
Type: "transaction_relay_policy",
Body: TransactionRelayPolicyMessage{
MinFee: MinFeeCruzbits,
MinAmount: MinAmountCruzbits,
},
}
case "get_work":
var gw GetWorkMessage
if err := json.Unmarshal(body, &gw); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
log.Printf("Received get_work message, from: %s\n", p.conn.RemoteAddr())
getWorkChan <- gw
case "submit_work":
var sw SubmitWorkMessage
if err := json.Unmarshal(body, &sw); err != nil {
log.Printf("Error: %s, from: %s\n", err, p.conn.RemoteAddr())
return
}
if sw.Header == nil {
log.Printf("Error: received nil header, from: %s\n", p.conn.RemoteAddr())
return
}
log.Printf("Received submit_work message, from: %s\n", p.conn.RemoteAddr())
submitWorkChan <- sw
default:
log.Printf("Unknown message: %s, from: %s\n", m.Type, p.conn.RemoteAddr())
}
case websocket.CloseMessage:
log.Printf("Received close message from: %s\n", p.conn.RemoteAddr())
break
}
}
}
// Handle a message from a peer indicating block inventory available for download
func (p *Peer) onInvBlock(id BlockID, index, length int, outChan chan<- Message) error {
log.Printf("Received inv_block: %s, from: %s\n", id, p.conn.RemoteAddr())
if length > maxBlocksPerInv {
return fmt.Errorf("%d blocks IDs is more than %d maximum per inv_block",
length, maxBlocksPerInv)
}
// is it on the ignore list?
if p.ignoreBlocks[id] {
log.Printf("Ignoring block %s, from: %s\n", id, p.conn.RemoteAddr())
return nil
}
// do we have it queued or inflight already?
if p.localDownloadQueue.Exists(id) || p.localInflightQueue.Exists(id) {
log.Printf("Block %s is already queued or inflight for download, from: %s\n",
id, p.conn.RemoteAddr())
return nil
}
// have we processed it?
branchType, err := p.ledger.GetBranchType(id)
if err != nil {
return err
}
if branchType != UNKNOWN {
log.Printf("Already processed block %s", id)
if length > 1 && index+1 == length {
// we might be on a deep side chain. this will get us the next 500 blocks
return p.sendFindCommonAncestor(&id, false, outChan)
}
return nil
}
if p.localDownloadQueue.Len() >= downloadQueueMax {
log.Printf("Too many blocks in the download queue %d, max: %d, for: %s",
p.localDownloadQueue.Len(), downloadQueueMax, p.conn.RemoteAddr())
// don't return an error just stop adding them to the queue
return nil
}
// add block to this peer's download queue
p.localDownloadQueue.Add(id, "")
// process the download queue
return p.processDownloadQueue(outChan)
}
// Handle a request for a block from a peer
func (p *Peer) onGetBlock(id BlockID, outChan chan<- Message) error {
log.Printf("Received get_block: %s, from: %s\n", id, p.conn.RemoteAddr())
return p.getBlock(id, outChan)
}
// Handle a request for a block by height from a peer
func (p *Peer) onGetBlockByHeight(height int64, outChan chan<- Message) error {
log.Printf("Received get_block_by_height: %d, from: %s\n", height, p.conn.RemoteAddr())
id, err := p.ledger.GetBlockIDForHeight(height)
if err != nil {
// not found
outChan <- Message{Type: "block"}
return err
}
if id == nil {
// not found
outChan <- Message{Type: "block"}
return fmt.Errorf("No block found at height %d", height)
}
return p.getBlock(*id, outChan)
}
func (p *Peer) getBlock(id BlockID, outChan chan<- Message) error {
// fetch the block
blockJson, err := p.blockStore.GetBlockBytes(id)
if err != nil {
// not found
outChan <- Message{Type: "block", Body: BlockMessage{BlockID: &id}}
return err
}
if len(blockJson) == 0 {
// not found
outChan <- Message{Type: "block", Body: BlockMessage{BlockID: &id}}
return fmt.Errorf("No block found with ID %s", id)
}
// send out the raw bytes
body := []byte(`{"block_id":"`)
body = append(body, []byte(id.String())...)
body = append(body, []byte(`","block":`)...)
body = append(body, blockJson...)
body = append(body, []byte(`}`)...)
outChan <- Message{Type: "block", Body: json.RawMessage(body)}
// was this the last block in the inv we sent in response to a find common ancestor request?
if id == p.continuationBlockID {
log.Printf("Received get_block for continuation block %s, from: %s\n",
id, p.conn.RemoteAddr())
p.continuationBlockID = BlockID{}
// send an inv for our tip block to prompt the peer to
// send another find common ancestor request to complete its download of the chain.
tipID, _, err := p.ledger.GetChainTip()
if err != nil {
log.Printf("Error: %s\n", err)
return nil
}
if tipID != nil {
outChan <- Message{Type: "inv_block", Body: InvBlockMessage{BlockIDs: []BlockID{*tipID}}}
}
}
return nil
}
// Handle receiving a block from a peer. Returns true if the block was newly processed and accepted.
func (p *Peer) onBlock(block *Block, ibd bool, outChan chan<- Message) (bool, error) {
// the message has the ID in it but we can't trust that.
// it's provided as convenience for trusted peering relationships only
id, err := block.ID()
if err != nil {
return false, err
}
log.Printf("Received block: %s, from: %s\n", id, p.conn.RemoteAddr())
blockInFlight, ok := p.localInflightQueue.Peek()
if !ok || blockInFlight != id {
// disconnect misbehaving peer
p.conn.Close()
return false, fmt.Errorf("Received unrequested block")
}
// don't process low difficulty blocks
if ibd == false && CheckpointsEnabled && block.Header.Height < LatestCheckpointHeight {
// don't disconnect them. they may need us to find out about the real chain
p.localInflightQueue.Remove(id, "")
p.globalInflightQueue.Remove(id, p.conn.RemoteAddr().String())
// ignore future inv_blocks for this block
p.ignoreBlocks[id] = true
if len(p.ignoreBlocks) > maxBlocksPerInv {
// they're intentionally sending us bad blocks
log.Printf("Disconnecting %s, max ignore list size exceeded\n", p.conn.RemoteAddr().String())
p.conn.Close()
}
return false, fmt.Errorf("Block %s height %d less than latest checkpoint height %d",
id, block.Header.Height, LatestCheckpointHeight)
}
var accepted bool
// is it an orphan?
header, _, err := p.blockStore.GetBlockHeader(block.Header.Previous)
if err != nil || header == nil {
p.localInflightQueue.Remove(id, "")
p.globalInflightQueue.Remove(id, p.conn.RemoteAddr().String())
if err != nil {
return false, err
}
log.Printf("Block %s is an orphan, sending find_common_ancestor to: %s\n",
id, p.conn.RemoteAddr())
// send a find common ancestor request
if err := p.sendFindCommonAncestor(nil, false, outChan); err != nil {
return false, err
}
} else {
// process the block
if err := p.processor.ProcessBlock(id, block, p.conn.RemoteAddr().String()); err != nil {
// disconnect a peer that sends us a bad block
p.conn.Close()
return false, err
}
// newly accepted block
accepted = true
// remove it from the inflight queues only after we process it
p.localInflightQueue.Remove(id, "")
p.globalInflightQueue.Remove(id, p.conn.RemoteAddr().String())
}
// see if there are any more blocks to download right now
if err := p.processDownloadQueue(outChan); err != nil {
return false, err
}
return accepted, nil
}
// Try requesting blocks that are in the download queue
func (p *Peer) processDownloadQueue(outChan chan<- Message) error {
// fill up as much of the inflight queue as possible
var queued int
for p.localInflightQueue.Len() < inflightQueueMax {
// next block to download
blockToDownload, ok := p.localDownloadQueue.Peek()
if !ok {
// no more blocks in the queue
break
}
// double-check if it's been processed since we last checked
branchType, err := p.ledger.GetBranchType(blockToDownload)
if err != nil {
return err
}
if branchType != UNKNOWN {
// it's been processed. remove it and check the next one
log.Printf("Block %s has been processed, removing from download queue for: %s\n",
blockToDownload, p.conn.RemoteAddr().String())
p.localDownloadQueue.Remove(blockToDownload, "")
continue
}
// add block to the global inflight queue with this peer as the owner
if p.globalInflightQueue.Add(blockToDownload, p.conn.RemoteAddr().String()) == false {
// another peer is downloading it right now.
// wait to see if they succeed before trying to download any others
log.Printf("Block %s is being downloaded already from another peer\n", blockToDownload)
break
}
// pop it off the local download queue
p.localDownloadQueue.Remove(blockToDownload, "")
// mark it inflight locally
p.localInflightQueue.Add(blockToDownload, "")
queued++
// request it
log.Printf("Sending get_block for %s, to: %s\n", blockToDownload, p.conn.RemoteAddr())
outChan <- Message{Type: "get_block", Body: GetBlockMessage{BlockID: blockToDownload}}
}
if queued > 0 {
log.Printf("Requested %d block(s) for download, from: %s", queued, p.conn.RemoteAddr())
log.Printf("Queue size: %d, peer inflight: %d, global inflight: %d, for: %s\n",
p.localDownloadQueue.Len(), p.localInflightQueue.Len(), p.globalInflightQueue.Len(), p.conn.RemoteAddr())
}
return nil
}