-
Notifications
You must be signed in to change notification settings - Fork 108
/
bitcoin_manager.go
2115 lines (1833 loc) · 76.7 KB
/
bitcoin_manager.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
package lib
import (
"bytes"
"encoding/hex"
"fmt"
"math/big"
mrand "math/rand"
"net"
"reflect"
"strconv"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/dgraph-io/badger/v3"
merkletree "github.com/laser/go-merkle-tree"
"github.com/pkg/errors"
"github.com/btcsuite/btcd/addrmgr"
btcdchain "github.com/btcsuite/btcd/blockchain"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/go-socks/socks"
"github.com/golang/glog"
deadlock "github.com/sasha-s/go-deadlock"
)
// bitcoin_manager.go handles all of the logic around connecting to Bitcoin nodes
// and downloading the Bitcoin header chain. Once it has a header chain with enough
// work on it, it notifies the Server, which takes things from there. In addition to
// syncing the header chain, the bitcoin_manager also downloads any new Bitcoin blocks
// as they are mined and searches their transactions for any that send money to the
// burn address. A good place to start in this file is _startSync() and _loop().
var (
// Note: Can be updated by various functions. It's a global variable sorry.
// TODO: We can turn this into a struct if we have more command-specific timeouts
// and pass it as an argument down the call stack.
BitcoinGetHeadersTimeout = 3 * time.Second
BitcoinHeaderUpdateInterval = 5 * time.Second
)
type ExpectedBitcoinResponse struct {
TimeExpected time.Time
Command string
}
type BroadcastTxn struct {
Txn *wire.MsgTx
// Keep track of the time added in case we want to expire broadcast transactions
// after some time.
TimeAdded time.Time
// Indicates whether the transaction has ever been broadcast to a peer.
WasBroadcast bool
}
type SwitchPeerMsg struct {
NewAddr string
ReplyChan chan error
}
type BitcoinManager struct {
db *badger.DB
params *BitCloutParams
timeSource btcdchain.MedianTimeSource
btcDataDir string
// The connection we're currently downloading headers from.
syncConn net.Conn
// Channel we send updates on. This helps notify whoever is interested
// whenever a block is added or we do a reorg. Can also be used to send
// BtcExchange transactions that get fashioned out of Bitcoin blocks.
updateChan chan *ServerMessage
// Used to select a node to download headers from.
addrMgr *addrmgr.AddrManager
// These should only be accessed after acquiring the BitcoinManagerLock.
//
// headerIndex contains a reference to all Bitcoin headers we've downloaded including
// ones that are not on the main chain.
BitcoinHeaderIndexLock deadlock.RWMutex
headerIndex map[BlockHash]*BlockNode
// bestHeaderChain is a slice of sequential Bitcoin headers on the main chain.
bestHeaderChain []*BlockNode
// bestHeaderChainMap is a map of all of the Bitcoin headers on the main chain.
bestHeaderChainMap map[BlockHash]*BlockNode
ExpectedResponsesLock deadlock.RWMutex
expectedResponses []*ExpectedBitcoinResponse
// A channel that services outside the BitcoinManager can use to broadcast
// transactions. Adding a transaction to this channel will cause it to get
// broadcast to the currently active Peer if one is set. This is a best-effort
// process.
broadcastBitcoinTxnChan chan *wire.MsgTx
// A channel that can be used to request a particular Bitcoin transaction from
// a peer. Note that Bitcoin nodes generally only provide mempool txns through
// this endpoint.
requestTxnChan chan chainhash.Hash
// A channel that services outside the BitcoinManager can use to request that
// a particular Bitcoin block be downloaded from a Peer and processed by the
// BitcoinManager.
requestBlockChan chan chainhash.Hash
// A channel that takes new <IP>:<Port> strings to connect to. When an address
// is found on this channel, the existing peer is dropped and a new peer is
// connected to. If a connection to the new peer fails then the switch is not
// completed.
SwitchPeerChan chan *SwitchPeerMsg
// When set, the BitcoinManager connects directly to this peer and doesn't
// consider connecting to any other peers.
connectPeer string
}
func (bm *BitcoinManager) GetAddrManager() *addrmgr.AddrManager {
return bm.addrMgr
}
func (bm *BitcoinManager) SyncConn() net.Conn {
return bm.syncConn
}
func (bm *BitcoinManager) ResetBitcoinHeaderIndex() error {
bm.BitcoinHeaderIndexLock.Lock()
defer bm.BitcoinHeaderIndexLock.Unlock()
return bm._resetBitcoinHeaderIndex()
}
func (bm *BitcoinManager) _resetBitcoinHeaderIndex() error {
// Delete any nodes that exist in the db. We check for this by checking to see
// if a BestHash is set.
bestHash := DbGetBestHash(bm.db, ChainTypeBitcoinHeader)
if bestHash != nil {
// TODO: Make this code less race-ey. I think if you stop the node during the point
// at which it's deleting nodes you could put the db in an unworkable state. Not a
// big deal, but annoying for the user because she may have to reset everything.
headerIndex, err := GetBlockIndex(bm.db, true /*bitcoinNodes*/)
if err != nil {
return errors.Wrapf(err, "BitcoinManager._resetBitcoinHeaderIndex: Problem "+
"loading existing Bitcoin node index: ")
}
nodesToDelete := []*BlockNode{}
for _, node := range headerIndex {
nodesToDelete = append(nodesToDelete, node)
}
if err := DbBulkDeleteHeightHashToNodeInfo(
nodesToDelete, bm.db, true /*bitcoinNodes*/); err != nil {
return errors.Wrapf(err, "BitcoinManager._resetBitcoinHeaderIndex: Problem "+
"deleting existing nodes from the db: %v", nodesToDelete)
}
}
// Put the start node in the HeightHashToNodeInfo index.
// <height uin32, blockhash BlockHash> -> <node info>
if err := bm._writeBitcoinNodeToDB(bm.params.BitcoinStartBlockNode); err != nil {
return errors.Wrapf(err,
"BitcoinManager.NewBitcoinManager: Problem calling _writeBitcoinNodeToDB"+
"for start node %v: ", bm.params.BitcoinStartBlockNode)
}
// Put the start node's hash as the best hash.
if err := PutBestHash(bm.params.BitcoinStartBlockNode.Hash,
bm.db, ChainTypeBitcoinHeader); err != nil {
return errors.Wrapf(err, "BitcoinManager.NewBitcoinManager: Problem "+
"putting best hash for start node: %v", bm.params.BitcoinStartBlockNode)
}
// No locks acquired because caller needs to acquire it.
bm.headerIndex[*bm.params.BitcoinStartBlockNode.Hash] = bm.params.BitcoinStartBlockNode
bm.bestHeaderChain = []*BlockNode{bm.params.BitcoinStartBlockNode}
bm.bestHeaderChainMap[*bm.params.BitcoinStartBlockNode.Hash] = bm.params.BitcoinStartBlockNode
return nil
}
func (bm *BitcoinManager) SetHeaderIndexAndBestChainListMap(
bestChain []*BlockNode, headerIndex map[BlockHash]*BlockNode) {
bm.BitcoinHeaderIndexLock.Lock()
defer bm.BitcoinHeaderIndexLock.Unlock()
bm.bestHeaderChain = bestChain
bm.headerIndex = headerIndex
for _, bestChainNode := range bm.bestHeaderChain {
bm.bestHeaderChainMap[*bestChainNode.Hash] = bestChainNode
}
}
func NewBitcoinManager(_db *badger.DB, _params *BitCloutParams,
_timeSource btcdchain.MedianTimeSource, _btcDataDir string,
_updateChan chan *ServerMessage, _connectPeer string) (
*BitcoinManager, error) {
bm := &BitcoinManager{
db: _db,
params: _params,
timeSource: _timeSource,
btcDataDir: _btcDataDir,
updateChan: _updateChan,
addrMgr: addrmgr.New(_btcDataDir, net.LookupIP),
headerIndex: make(map[BlockHash]*BlockNode),
bestHeaderChain: []*BlockNode{},
bestHeaderChainMap: make(map[BlockHash]*BlockNode),
broadcastBitcoinTxnChan: make(chan *wire.MsgTx),
requestBlockChan: make(chan chainhash.Hash),
requestTxnChan: make(chan chainhash.Hash),
SwitchPeerChan: make(chan *SwitchPeerMsg),
connectPeer: _connectPeer,
}
// Get the best hash we're currently aware of. If it doesn't exist, initialize
// the db with the start node.
bestHash := DbGetBestHash(bm.db, ChainTypeBitcoinHeader)
if bestHash == nil {
// If there's no best hash set, reset the db and set the best hash to be the
// new tip.
if err := bm.ResetBitcoinHeaderIndex(); err != nil {
return nil, errors.Wrapf(err, "BitcoinManager.NewBitcoinManager: Problem "+
"initializing header index: ")
}
} else {
// At this point we are confident that a best hash and a best chain exist in our
// database so get them.
headerIndex, err := GetBlockIndex(bm.db, true /*bitcoinNodes*/)
if err != nil {
return nil, errors.Wrapf(err, "BitcoinManager.NewBitcoinManager: Problem "+
"loading Bitcoin node index: ")
}
bestNode, bestNodeExists := headerIndex[*bestHash]
if !bestNodeExists {
return nil, fmt.Errorf("BitcoinManager.NewBitcoinManager: Problem: Best hash "+
"%v is not present in header index, which has %d items in it",
bestHash, len(headerIndex))
}
// Set the header index and the best chain list and map.
bestChain, err := GetBestChain(bestNode, headerIndex)
if err != nil {
return nil, errors.Wrapf(err, "BitcoinManager.NewBitcoinManager: Problem getting "+
"best chain for node %v: ", bestNode)
}
// Note the headerIndex might have some non-main-chain blocks in it that we need
// to exclude when setting the bestChainMap.
bm.SetHeaderIndexAndBestChainListMap(bestChain, headerIndex)
}
return bm, nil
}
func (bm *BitcoinManager) HeaderTip() *BlockNode {
bm.BitcoinHeaderIndexLock.RLock()
defer bm.BitcoinHeaderIndexLock.RUnlock()
return bm._headerTip()
}
func (bm *BitcoinManager) _headerTip() *BlockNode {
return bm.bestHeaderChain[len(bm.bestHeaderChain)-1]
}
// _newNetAddress attempts to extract the IP address and port from the passed
// net.Addr interface and create a bitcoin NetAddress structure using that
// information.
func _newNetAddress(addr net.Addr, services wire.ServiceFlag) (*wire.NetAddress, error) {
// addr will be a net.TCPAddr when not using a proxy.
if tcpAddr, ok := addr.(*net.TCPAddr); ok {
ip := tcpAddr.IP
port := uint16(tcpAddr.Port)
na := wire.NewNetAddressIPPort(ip, port, services)
return na, nil
}
// addr will be a socks.ProxiedAddr when using a proxy.
if proxiedAddr, ok := addr.(*socks.ProxiedAddr); ok {
ip := net.ParseIP(proxiedAddr.Host)
if ip == nil {
ip = net.ParseIP("0.0.0.0")
}
port := uint16(proxiedAddr.Port)
na := wire.NewNetAddressIPPort(ip, port, services)
return na, nil
}
// For the most part, addr should be one of the two above cases, but
// to be safe, fall back to trying to parse the information from the
// address string as a last resort.
host, portStr, err := net.SplitHostPort(addr.String())
if err != nil {
return nil, err
}
ip := net.ParseIP(host)
port, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, err
}
na := wire.NewNetAddressIPPort(ip, uint16(port), services)
return na, nil
}
// writeMessage sends a bitcoin message to the peer with logging.
func (bm *BitcoinManager) writeMessage(conn net.Conn, msg wire.Message, params *BitCloutParams) error {
_, err := wire.WriteMessageWithEncodingN(conn, msg,
params.BitcoinProtocolVersion, wire.BitcoinNet(params.BitcoinBtcdParams.Net),
wire.BaseEncoding)
if err != nil {
return err
}
// The following messages require a prompt response.
if msg.Command() == "getheaders" {
bm._addExpectedResponse("headers", time.Now().Add(BitcoinGetHeadersTimeout))
}
return err
}
func (bm *BitcoinManager) readMessage(conn net.Conn, params *BitCloutParams) (wire.Message, []byte, error) {
_, msg, buf, err := wire.ReadMessageWithEncodingN(conn,
params.BitcoinProtocolVersion, wire.BitcoinNet(params.BitcoinBtcdParams.Net),
wire.BaseEncoding)
if err != nil {
return nil, nil, err
}
// The following messages allow us to dequeue an expected response.
if msg.Command() == "headers" {
bm._removeEarliestExpectedResponse(msg.Command())
}
return msg, buf, nil
}
// _minUint32 is a helper function to return the minimum of two uint32s.
// This avoids a math import and the need to cast to floats.
func _minUint32(a, b uint32) uint32 {
if a < b {
return a
}
return b
}
// readRemoteVersionMsg waits for the next message to arrive from the remote
// peer. If the next message is not a version message or the version is not
// acceptable then return an error.
func (bm *BitcoinManager) readRemoteVersionMsg(conn net.Conn, params *BitCloutParams) (_minVersion uint32, _err error) {
// Read their version message.
remoteMsg, _, err := bm.readMessage(conn, params)
if err != nil {
return 0, err
}
// Notify and disconnect clients if the first message is not a version
// message.
msg, ok := remoteMsg.(*wire.MsgVersion)
if !ok {
return 0, fmt.Errorf("BitcoinManager.readRemoteVersionMsg: First message received was not a version message")
}
advertisedProtoVer := uint32(msg.ProtocolVersion)
minVersion := _minUint32(params.BitcoinProtocolVersion, advertisedProtoVer)
if msg.Services&wire.SFNodeNetwork == 0 {
return 0, fmt.Errorf("BitcoinManager.readRemoteVersionMsg: Full node is required as sync peer")
}
return minVersion, nil
}
// localVersionMsg creates a version message that can be used to send to the
// remote peer.
func localVersionMsg(conn net.Conn, tipHeight int32, params *BitCloutParams) (*wire.MsgVersion, error) {
theirNA, err := _newNetAddress(conn.RemoteAddr(), wire.SFNodeNetwork)
if err != nil {
return nil, err
}
// Create a wire.NetAddress with only the services set to use as the
// "addrme" in the version message.
//
// Older nodes previously added the IP and port information to the
// address manager which proved to be unreliable as an inbound
// connection from a peer didn't necessarily mean the peer itself
// accepted inbound connections.
//
// Also, the timestamp is unused in the version message.
ourNA := &wire.NetAddress{
Services: 0,
}
// Generate a unique nonce for this peer so self connections can be
// detected. This is accomplished by adding it to a size-limited map of
// recently seen nonces.
nonce := uint64(mrand.Int63())
// Version message.
msg := wire.NewMsgVersion(ourNA, theirNA, nonce, tipHeight)
msg.AddUserAgent(params.UserAgent, "1.0", []string{}...)
// Advertise local services.
msg.Services = 0
// Advertise our max supported protocol version.
msg.ProtocolVersion = int32(params.BitcoinProtocolVersion)
// Advertise if inv messages for transactions are desired.
// We don't want inv messages from our Bitcoin peer.
msg.DisableRelayTx = true
return msg, nil
}
func (bm *BitcoinManager) AddSeeds() {
// These constants are used by the DNS seed code to pick a random last
// seen time.
secondsIn3Days := int32(24 * 60 * 60 * 3)
secondsIn4Days := int32(24 * 60 * 60 * 4)
glog.Debugf("BitcoinManager.AddSeeds: Starting DNS discovery...")
for _, dnsseed := range bm.params.BitcoinDNSSeeds {
host := dnsseed
go func(host string) {
randSource := mrand.New(mrand.NewSource(time.Now().UnixNano()))
glog.Tracef("BitcoinManager.AddSeeds: Calling LookupIP on %s", host)
seedpeers, err := net.LookupIP(host)
if err != nil {
glog.Tracef("BitcoinManager.AddSeeds: DNS discovery failed on seed %s: %v", host, err)
return
}
numPeers := len(seedpeers)
glog.Tracef("BitcoinManager.AddSeeds: %d addresses found from DNS seed %s", numPeers, host)
if numPeers == 0 {
return
}
addresses := make([]*wire.NetAddress, len(seedpeers))
// if this errors then we have *real* problems
intPort, _ := strconv.Atoi(bm.params.BitcoinDefaultPort)
for i, peer := range seedpeers {
addresses[i] = wire.NewNetAddressTimestamp(
// bitcoind seeds with addresses from
// a time randomly selected between 3
// and 7 days ago.
time.Now().Add(-1*time.Second*time.Duration(secondsIn3Days+
randSource.Int31n(secondsIn4Days))),
0, peer, uint16(intPort))
}
glog.Tracef("BitcoinManager.AddSeeds: Adding %d addresses to addrmgr for host %s",
len(addresses), host)
if len(addresses) > 0 {
bm.addrMgr.AddAddresses(addresses, addresses[0])
//bm.addrMgr.AddAddressesRelaxed(addIPNetAddrs, addIPNetAddrs[0])
}
}(host)
}
}
func _getRandomPeer(addrMgr *addrmgr.AddrManager, dialTimeout time.Duration) (net.Conn, *wire.NetAddress) {
glog.Debugf("BitcoinManager.startSync: Trying to find Bitcoin address to connect to")
// Choose a random Peer from the address manager.
randomAddr := addrMgr.GetAddress()
if randomAddr == nil {
glog.Debugf("BitcoinManager.startSync: No Bitcoin address found to connect to.")
return nil, nil
}
glog.Debugf("BitcoinManager.startSync: Found address to connect to!")
// If we get here we found a random address to try.
ipNetAddr := randomAddr.NetAddress()
netAddr := net.TCPAddr{
IP: ipNetAddr.IP,
Port: int(ipNetAddr.Port),
}
// Update the addrmgr with the fact that we're attempting this address.
glog.Debugf("BitcoinManager.startSync: Attempting to connect to addr: %v", netAddr)
addrMgr.Attempt(ipNetAddr)
var err error
conn, err := net.DialTimeout(netAddr.Network(), netAddr.String(), dialTimeout)
if err != nil {
// If we failed to connect to this peer, get a new address and try again.
glog.Debugf("BitcoinManager.startSync: Connection to addr (%v) failed: %v", netAddr, err)
return nil, nil
}
// We were able to dial successfully so we'll break out now.
glog.Debugf("BitcoinManager.startSync: Connected to addr: %v", conn.RemoteAddr().String())
// Mark the address as connected in the addrmgr.
addrMgr.Connected(ipNetAddr)
return conn, ipNetAddr
}
func (bm *BitcoinManager) _negotiateVersion(conn net.Conn, height int32, params *BitCloutParams) error {
// Send the Peer a version message and wait for a response.
// If the response is positive, then start downloading headers from the Peer.
// If not, then continue and try the whole process over again.
glog.Debugf("BitcoinManager.startSync: Writing version message: %v", conn.RemoteAddr().String())
verMsg, err := localVersionMsg(conn, height, params)
if err != nil {
errorMsg := "BitcoinManager.startSync: Problem writing version message"
glog.Debugf(errorMsg)
return fmt.Errorf(errorMsg)
}
bm.writeMessage(conn, verMsg, params)
readVersionChan := make(chan error)
go func() {
_, err := bm.readRemoteVersionMsg(conn, params)
readVersionChan <- err
}()
// Negotiate the protocol within the specified negotiateTimeout.
glog.Debugf("BitcoinManager.startSync: Waiting for version response: %v", conn.RemoteAddr().String())
select {
case err := <-readVersionChan:
if err != nil {
// If we have an error reading the version, sleep and try again
// with a new Peer.
errorMsg := fmt.Sprintf("BitcoinManager.startSync: Error in version response for "+
"addr %v: %v. Sleeping and trying another address.",
conn.RemoteAddr().String(), err)
glog.Debugf(errorMsg)
return fmt.Errorf(errorMsg)
}
case <-time.After(params.DialTimeout):
// Same goes for if we time out.
errorMsg := fmt.Sprintf("BitcoinManager.startSync: Version response timeout for addr %v. "+
"Sleeping and trying another address.", conn.RemoteAddr().String())
glog.Debugf(errorMsg)
return fmt.Errorf(errorMsg)
}
glog.Debugf("BitcoinManager.startSync: Connected to Bitcoin peer: %s", conn.RemoteAddr())
// Send a verack to the peer.
glog.Debugf("BitcoinManager.startSync: Writing verack: %s.", conn.RemoteAddr().String())
bm.writeMessage(conn, wire.NewMsgVerAck(), params)
// If we get here we should have completed a successful Bitcoin version
// negotiation with the Peer.
glog.Debugf("BitcoinManager.startSync: Version negotiation with addr complete: %s.",
conn.RemoteAddr().String())
return nil
}
func _difficultyBitsToHash(diffBits uint32) (_diffHash *BlockHash) {
diffBigint := btcdchain.CompactToBig(diffBits)
return BigintToHash(diffBigint)
}
func _difficultyHashToBits(diffHash *BlockHash) (_diffBits uint32) {
diffBigint := HashToBigint(diffHash)
return btcdchain.BigToCompact(diffBigint)
}
// findPrevTestNetDifficulty returns the difficulty of the previous block which
// did not have the special testnet minimum difficulty rule applied.
//
// This function MUST be called with the chain state lock held (for writes).
func _findPrevTestNetDifficulty(startNode *BlockNode, params *BitCloutParams) *BlockHash {
powLimitHash := _difficultyBitsToHash(params.BitcoinPowLimitBits)
// Search backwards through the chain for the last block without
// the special rule applied.
iterNode := startNode
// The node stores a difficulty block hash.
// Convert it to bigint.
// Convert the bigint to bits.
for iterNode != nil && iterNode.Height%params.BitcoinBlocksPerRetarget != 0 &&
*iterNode.DifficultyTarget == *powLimitHash {
iterNode = iterNode.Parent
}
// Return the found difficulty or the minimum difficulty if no
// appropriate block was found.
lastDiffHash := powLimitHash
if iterNode != nil {
lastDiffHash = iterNode.DifficultyTarget
}
return lastDiffHash
}
// _calcNextRequiredDifficulty calculates the required difficulty for the block
// after the passed previous block node based on the difficulty retarget rules.
// This function differs from the exported CalcNextRequiredDifficulty in that
// the exported version uses the current best chain as the previous block node
// while this function accepts any block node.
func _calcNextRequiredDifficulty(lastNode *BlockNode, newBlockTime time.Time, params *BitCloutParams) (*BlockHash, error) {
// Genesis block.
if lastNode == nil {
return _difficultyBitsToHash(params.BitcoinPowLimitBits), nil
}
// Return the previous block's difficulty requirements if this block
// is not at a difficulty retarget interval.
if (lastNode.Height+1)%params.BitcoinBlocksPerRetarget != 0 {
// For networks that support it, allow special reduction of the
// required difficulty once too much time has elapsed without
// mining a block.
if params.BitcoinMinDiffReductionTime != 0 {
// Return minimum difficulty when more than the desired
// amount of time has elapsed without mining a block.
reductionTimeSecs := int64(params.BitcoinMinDiffReductionTime /
time.Second)
allowMinTime := int64(lastNode.Header.TstampSecs) + reductionTimeSecs
if newBlockTime.Unix() > allowMinTime {
return _difficultyBitsToHash(params.BitcoinPowLimitBits), nil
}
// The block was mined within the desired timeframe, so
// return the difficulty for the last block which did
// not have the special minimum difficulty rule applied.
return _findPrevTestNetDifficulty(lastNode, params), nil
}
// For the main network (or any unrecognized networks), simply
// return the previous block's difficulty requirements.
return lastNode.DifficultyTarget, nil
}
// Get the block node at the previous retarget (targetTimespan days
// worth of blocks).
firstNode := lastNode.RelativeAncestor(params.BitcoinBlocksPerRetarget - 1)
if firstNode == nil {
return nil, fmt.Errorf("_calcNextRequiredDifficulty: Unable to obtain previous retarget block")
}
// Limit the amount of adjustment that can occur to the previous
// difficulty.
actualTimespan := uint32(lastNode.Header.TstampSecs - firstNode.Header.TstampSecs)
adjustedTimespan := actualTimespan
if actualTimespan < params.BitcoinMinRetargetTimespanSecs {
adjustedTimespan = params.BitcoinMinRetargetTimespanSecs
} else if actualTimespan > params.BitcoinMaxRetargetTimespanSecs {
adjustedTimespan = params.BitcoinMaxRetargetTimespanSecs
}
// Calculate new target difficulty as:
// currentDifficulty * (adjustedTimespan / targetTimespan)
// The result uses integer division which means it will be slightly
// rounded down. Bitcoind also uses integer division to calculate this
// result.
oldTarget := HashToBigint(lastNode.DifficultyTarget)
newTarget := new(big.Int).Mul(oldTarget, big.NewInt(int64(adjustedTimespan)))
newTarget.Div(newTarget, big.NewInt(int64(params.BitcoinTargetTimespanSecs)))
// Limit new value to the proof of work limit.
powLimitBigint := btcdchain.CompactToBig(params.BitcoinPowLimitBits)
if newTarget.Cmp(powLimitBigint) > 0 {
newTarget.Set(powLimitBigint)
}
// Convert the hash to bits so we lose the precision (yes *lose*) and then
// go back.
newTargetHash := BigintToHash(newTarget)
newTargetBits := _difficultyHashToBits(newTargetHash)
return _difficultyBitsToHash(newTargetBits), nil
}
// ProcessBitcoinHeaderQuick processes a Bitcoin header without checking its proof
// of work, leaving that to be done in a later post-processing step.
//
// Holds the BitcoinHeaderIndexLock for writing.
func (bm *BitcoinManager) ProcessBitcoinHeaderQuick(bitcoinHeader *wire.BlockHeader, params *BitCloutParams) (
_isMainChain bool, _isOrphan bool, _err error) {
bm.BitcoinHeaderIndexLock.Lock()
defer bm.BitcoinHeaderIndexLock.Unlock()
headerHash := (BlockHash)(bitcoinHeader.BlockHash())
parentHash := (BlockHash)(bitcoinHeader.PrevBlock)
// Reject the header if it is more than N seconds in the future.
tstampDiff := bitcoinHeader.Timestamp.Unix() - bm.timeSource.AdjustedTime().Unix()
if tstampDiff > int64(params.BitcoinMaxTstampOffsetSeconds) {
return false, false, HeaderErrorBlockTooFarInTheFuture
}
parentNode, parentNodeExists := bm.headerIndex[parentHash]
if !parentNodeExists {
// This block is an orphan if its parent doesn't exist and we don't
// process unconnectedTxns.
return false, true, nil
}
// Verify that the parent node is the tip.
if *parentNode.Hash != *bm._headerTip().Hash {
return false, false, fmt.Errorf("BitcoinManager.ProcessBitcoinHeaderQuick: "+
"Processing header %v with height %v with parent %v that is not equal to the current "+
"tip %v; this should never happen",
bitcoinHeader, parentNode.Height+1, parentNode, bm._headerTip())
}
height := parentNode.Height + 1
if height%params.BitcoinBlocksPerRetarget == 0 {
glog.Tracef("BitcoinManager.ProcessBitcoinHeaderQuick: Header at retarget point: "+
"DiffBits: %d, Height: %d, TstampSecs %d, Hash: %v\n",
bitcoinHeader.Bits,
height,
bitcoinHeader.Timestamp.Unix(),
bitcoinHeader.BlockHash())
}
merkleRootHash := (BlockHash)(bitcoinHeader.MerkleRoot)
newNode := NewBlockNode(
parentNode,
&headerHash,
// Note the height is always one greater than the parent node.
parentNode.Height+1,
_difficultyBitsToHash(bitcoinHeader.Bits),
big.NewInt(0),
// We are bastardizing the BitClout header to store Bitcoin information here. However,
// it is important to note that they are similar enough such that if one were to
// take the MsgBitCloutHeader information stored here and convert it to a wire.BlockHeader,
// the latter should produce a hash that lines up with the hash we're storing above.
&MsgBitCloutHeader{
Version: uint32(bitcoinHeader.Version),
PrevBlockHash: parentNode.Hash,
TransactionMerkleRoot: &merkleRootHash,
TstampSecs: uint64(bitcoinHeader.Timestamp.Unix()),
Height: uint64(parentNode.Height + 1),
Nonce: uint64(bitcoinHeader.Nonce),
},
StatusNone,
)
bm.headerIndex[*newNode.Hash] = newNode
bm.bestHeaderChain, bm.bestHeaderChainMap = updateBestChainInMemory(
bm.bestHeaderChain, bm.bestHeaderChainMap, []*BlockNode{}, []*BlockNode{newNode})
return true, false, nil
}
func (bm *BitcoinManager) _computePow(tstamp time.Time, headerHash *BlockHash,
parentNode *BlockNode, params *BitCloutParams, optionalDifficultyBits uint32) (
_diffTarget *BlockHash, _cumWork *big.Int, _err error) {
// Check that the proof of work beats the difficulty as calculated from
// the parent block. Note that if the parent block is in the block index
// then it has necessarily had its difficulty validated, and so using it to
// do this check makes sense from an induction standpoint.
diffTarget, err := _calcNextRequiredDifficulty(
parentNode, tstamp, params)
if err != nil {
return nil, nil, errors.Wrapf(err,
"_computePow: Problem computing difficulty "+
"target from parent block %s", hex.EncodeToString(parentNode.Hash[:]))
}
diffTargetBigint := HashToBigint(diffTarget)
// If some difficulty bits are set, check that the difficulty target as
// computed from the parent block matches what is set in the bits.
if optionalDifficultyBits != 0 {
difficultyBitsBigint := btcdchain.CompactToBig(optionalDifficultyBits)
if difficultyBitsBigint.Cmp(diffTargetBigint) != 0 &&
(*diffTarget != *_difficultyBitsToHash(params.BitcoinPowLimitBits)) {
glog.Errorf("_computePow: Target difficulty according to bits %v is "+
"not consistent with target difficulty according to parent %v with "+
"height %d and hash %v", _difficultyBitsToHash(optionalDifficultyBits), diffTarget,
parentNode.Height+1, headerHash)
return nil, nil, HeaderErrorDifficultyBitsNotConsistentWithTargetDifficultyComputedFromParent
}
}
// Reverse the header hash to turn it into a bigint.
unreversedHeaderHash := BlockHash{}
for ii := range headerHash {
unreversedHeaderHash[ii] = headerHash[len(headerHash)-1-ii]
}
blockHashBigint := HashToBigint(&unreversedHeaderHash)
if diffTargetBigint.Cmp(blockHashBigint) < 0 {
glog.Errorf("_computePow: Block difficulty %v is greater than the target "+
"difficulty %v for height %d", &unreversedHeaderHash, diffTarget,
parentNode.Height+1)
return nil, nil, HeaderErrorBlockDifficultyAboveTarget
}
newWork := btcdchain.CalcWork(_difficultyHashToBits(diffTarget))
cumWork := newWork.Add(newWork, parentNode.CumWork)
return diffTarget, cumWork, nil
}
func (bm *BitcoinManager) _writeBitcoinNodeToDB(node *BlockNode) error {
// Store the new node in our node index in the db under the
// <height uin32, blockhash BlockHash> -> <node info>
// index.
if err := PutHeightHashToNodeInfo(node, bm.db, true /*bitcoinNodes*/); err != nil {
return errors.Wrapf(err,
"_writeBitcoinNodeToDB: Problem calling PutHeightHashToNodeInfo for node %v: ", node)
}
return nil
}
// Acquires the BitcoinHeaderIndexLock for writing.
func (bm *BitcoinManager) ProcessBitcoinHeaderFull(bitcoinHeader *wire.BlockHeader, params *BitCloutParams) (
_isMainChain bool, _isOrphan bool, _err error) {
bm.BitcoinHeaderIndexLock.Lock()
defer bm.BitcoinHeaderIndexLock.Unlock()
headerHash := (BlockHash)(bitcoinHeader.BlockHash())
parentHash := (BlockHash)(bitcoinHeader.PrevBlock)
// Start by checking if the header already exists in our node
// index. If it does, then return an error. We should generally
// expect that processHeader will only be called on headers we
// haven't seen before.
existingNode, nodeExists := bm.headerIndex[headerHash]
if nodeExists {
return false, false, errors.Wrapf(HeaderErrorDuplicateHeader,
"Duplicate header has height %v: ", existingNode.Height)
}
// If we're here then it means we're processing a header we haven't
// seen before.
// Reject the header if it is more than N seconds in the future.
tstampDiff := bitcoinHeader.Timestamp.Unix() - bm.timeSource.AdjustedTime().Unix()
if tstampDiff > int64(params.BitcoinMaxTstampOffsetSeconds) {
return false, false, HeaderErrorBlockTooFarInTheFuture
}
// Try to find this header's parent in our block index.
// If we can't find the parent then this header is an orphan and we
// can return early because we don't process unconnectedTxns.
parentNode, parentNodeExists := bm.headerIndex[parentHash]
if !parentNodeExists {
// This block is an orphan if its parent doesn't exist and we don't
// process unconnectedTxns.
return false, true, nil
}
// If the parent node is invalid then this header is invalid as well. Note that
// if the parent node exists then its header must either be BitcoinValidated or
// BitcoinValidateFailed.
parentHeader := parentNode.Header
parentIsValid := ((parentNode.Status & StatusBitcoinHeaderValidateFailed) == 0)
if parentHeader == nil || !parentIsValid {
return false, false, HeaderErrorInvalidParent
}
// Note that Bitcoin headers don't have heights so we don't check them.
// Note Bitcoin checks that the block's timestamp is greater than the median of
// the last 11 blocks but we forego this check because we're lazy. As long as
// a critical mass of Bitcoin nodes continues to care about this rule it will be
// enforced and our free-riding on their validation should be acceptable.
diffTarget, cumWork, err := bm._computePow(
bitcoinHeader.Timestamp, &headerHash, parentNode, params,
bitcoinHeader.Bits)
if err != nil {
return false, false, errors.Wrapf(
err, "ProcessBitcoinHeaderFull: Problem computing PoW: ")
}
// At this point the header seems sane so we store it in the db and add
// it to our in-memory block index. Note we're not doing this atomically.
// Worst-case, we have a header in our db with no pointer to it in our index,
// which isn't a big deal.
//
// Note in the calculation of CumWork below we are adding the work specified
// in the difficulty *target* rather than the work actually done to mine the
// block. There is a good reason for this, which is that it materially
// increases a miner's incentive to reveal their block immediately after it's
// been mined as opposed to try and play games where they withhold their block
// and try to mine on top of it before revealing it to everyone.
merkleRootHash := (BlockHash)(bitcoinHeader.MerkleRoot)
newNode := NewBlockNode(
parentNode,
&headerHash,
// Note the height is always one greater than the parent node.
parentNode.Height+1,
diffTarget,
cumWork,
// We are bastardizing the BitClout header to store Bitcoin information here. However,
// it is important to note that they are similar enough such that if one were to
// take the MsgBitCloutHeader information stored here and convert it to a wire.BlockHeader,
// the latter should produce a hash that lines up with the hash we're storing above.
&MsgBitCloutHeader{
Version: uint32(bitcoinHeader.Version),
PrevBlockHash: parentNode.Hash,
TransactionMerkleRoot: &merkleRootHash,
TstampSecs: uint64(bitcoinHeader.Timestamp.Unix()),
Height: uint64(parentNode.Height + 1),
Nonce: uint64(bitcoinHeader.Nonce),
},
StatusBitcoinHeaderValidated,
)
// If all went well with storing the header, set it in our in-memory
// index.
bm.headerIndex[*newNode.Hash] = newNode
// Update the header chain if this header has more cumulative work than
// the header chain's tip. Note that we can assume all ancestors of this
// header are valid at this point.
isMainChain := false
headerTip := bm._headerTip()
if headerTip.CumWork.Cmp(newNode.CumWork) < 0 {
isMainChain = true
// Get the blocks to attach and detach as a result of this operation.
_, detachBlocks, attachBlocks := GetReorgBlocks(headerTip, newNode)
// Update the best chain in memory.
bm.bestHeaderChain, bm.bestHeaderChainMap = updateBestChainInMemory(
bm.bestHeaderChain, bm.bestHeaderChainMap, detachBlocks, attachBlocks)
// Log if we had a large reorg. This should never happen.
if int64(len(detachBlocks)) > params.MinerBitcoinMinBurnWorkBlockss {
glog.Errorf("ProcessBitcoinHeaderFull: Bitcoin reorg detached %d blocks "+
"which is more than the maximum we expect %d. The BitClout chain could be "+
"corrupted at this point; consider wiping the data directory and rebooting "+
"the node from scratch", len(detachBlocks),
params.MinerBitcoinMinBurnWorkBlockss)
}
// Update the db to purge the detached blocks and write the attached blocks.
// Although we store side-chains in memory via the headerIndex, we don't store
// side chain blocks on the db. With the code below, we guarantee that we always
// write blocks when we attach them and delete blocks when we detach them, meaning
// that only the best chain blocks are actually stored in the db at any given time.
// This is true even given the antics of FullyValidateHeaders.
if err := DbBulkDeleteHeightHashToNodeInfo(
detachBlocks, bm.db, true /*bitcoinNodes*/); err != nil {
return false, false, errors.Wrapf(err, "ProcessBitcoinHeaderFull: Problem "+
"deleting detached nodes from the db: %v", detachBlocks)
}
for _, newlyAttachedNode := range attachBlocks {
if err := bm._writeBitcoinNodeToDB(newlyAttachedNode); err != nil {
return false, false, errors.Wrapf(err, "ProcessBitcoinHeaderFull: Problem "+
"writing new node to db: ")
}
}
// Update the db to reflect the new best Bitcoin chain.
if err := PutBestHash(&headerHash, bm.db, ChainTypeBitcoinHeader); err != nil {
return false, false, err
}
}
return isMainChain, false, nil
}
// Note that the amount of work must be determined based on the oldest
// time-current block that we have rather than the tip. If we aren't time-current
// or if the height passed in is greater than that of the oldest time-current
// Bitcoin block then a negative value, specifying the number of blocks this height
// is *behing* the oldest time-current block, is returned. When the height is
// equal to that of the oldest time-current block, zero is returned.
func (bm *BitcoinManager) GetBitcoinBurnWorkBlocks(blockHeight uint32) int64 {
return int64(bm.HeaderTip().Height) - int64(blockHeight)
}
func (bm *BitcoinManager) IsCurrent(considerCumWork bool) bool {
bm.BitcoinHeaderIndexLock.RLock()
defer bm.BitcoinHeaderIndexLock.RUnlock()
return bm._isCurrent(considerCumWork)
}
func (bm *BitcoinManager) _isCurrent(considerCumWork bool) bool {
headerTip := bm._headerTip()
return bm._isCurrentNode(headerTip, considerCumWork)
}
// - Min difficulty is reached
// - Latest block has a timestamp newer than 24 hours ago
func (bm *BitcoinManager) _isCurrentNode(node *BlockNode, considerCumWork bool) bool {
minChainWorkBytes, _ := hex.DecodeString(bm.params.BitcoinMinChainWorkHex)
minWorkBigint := BytesToBigint(minChainWorkBytes)
// Not current if the cumulative work is below the threshold.
if considerCumWork && node.CumWork.Cmp(minWorkBigint) < 0 {
//glog.Tracef("BitcoinManager.isCurrent: Header tip work %v less than "+
//"total min chain work %v", node.CumWork, minWorkBigint)
return false
}