-
Notifications
You must be signed in to change notification settings - Fork 1
/
ink-miner.go
1348 lines (1178 loc) · 36.8 KB
/
ink-miner.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
/*
An ink miner mines ink and disseminates blocks
Usage:
go run ink-miner.go [server ip:port] [pubKey] [privKey]
*/
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/md5"
"crypto/rand"
"crypto/x509"
"encoding/gob"
"encoding/hex"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"math/big"
"net"
"net/rpc"
"os"
"os/signal"
"sort"
"strconv"
"strings"
"sync"
"time"
"./blockartlib"
"math"
)
import _ "net/http/pprof"
const debugLocks = false
const logGetNodes = false
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// START OF INTERFACES //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
type MinerToMinerInterface interface {
FloodBlockToPeers(block *Block) error
FloodOpToPeers(op Operation) error
HeartbeatNeighbours() error
GetHeartbeats() error
GetBlockChain() error
FetchBlockChain(i string, blockchain *[]Block) error
ReceiveBlock(block *Block, reply *bool) error
ReceiveOp(op Operation, reply *bool) error
}
////// TCP RPC calls to make against server
/*
settings, err ← Register(address, publicKey)
Registers a new miner witMinerToMinerh an address for other miner to use to connect to it (returned in GetNodes call below)
and a public-key for this miner. Returns error, or if error is not set, then setting for this canvas instance.
Returns AddressAlreadyRegisteredError if the server has already registered this address.
Returns KeyAlreadyRegisteredError if the server already has a registration record for publicKey.
addrSet,err ← GetNodes(publicKey)
Returns addresses for a subset of miners in the system. Returns UnknownKeyError if the server does not know
a miner with this publicKey.
err ← HeartBeat(publicKey)
The server also listens for heartbeats from known miners. A miner must send a heartbeat to the server
every HeartBeat milliseconds (specified in settings from server) after calling Register, otherwise the server
will stop returning this miner's address/key to other miners.
Returns UnknownKeyError if the server does not know a miner with this publicKey.
*/
type MinerToServerInterface interface {
// makes RPC Register(localAddr, pubKey) call, and registers settings returned for canvas or returns error
Register() error
// Makes RPC GetNodes(pubKey) call, makes a call to ConnectToNeighbour for each returned addr, can return errors
GetNodes() error
// makes RPC HearBeat(pubKey) call, changes connected state accordingly which will return different errors for art node requests
HeartbeatServer() error
}
type MinerFromANodeInterface interface {
GetGenesisBlock(input string, hash *string) (err error)
GetChildren(hash string, childrenHashes *[]string) (err error)
}
type IMinerInterface interface {
// Just a disconnected error? other errors will be handled by methods called within mine
getLongestChain() (hash string)
Length(hash string) (err error)
ValidationCount(hash string) (err error)
Mine() error
}
type BlockInterface interface{}
// methods for validation, blockchain itself
type BlockChainInterface interface {
ValidateBlock(BlockInterface) error
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// END OF INTERFACES, START OF STRUCTS //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
type MinerToMiner struct{}
type MinerToServer struct{}
type MinerFromANode struct{}
type IMiner struct {
serverClient *rpc.Client
localAddr net.Addr
artAddr string
neighbours map[string]*rpc.Client
settings MinerNetSettings
key ecdsa.PrivateKey
}
type Operation struct {
Delete bool
SVG string
SVGHash SVGHash
Owner ecdsa.PublicKey
ValNum uint8
}
type SVGHash struct {
Hash []byte
R, S *big.Int
}
type Block struct {
PrevHash string
MinedBy ecdsa.PublicKey
Ops []Operation
Nonce string
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// END OF STRUCTS, START OF METHODS //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
func (art MinerFromANode) GetGenesisBlock(input string, hash *string) (err error) {
*hash = ink.settings.GenesisBlockHash // TODO: This hash does not have a block
return
}
type InvalidBlockHashError string
func (e InvalidBlockHashError) Error() string {
return fmt.Sprintf("BlockArt: Invalid block hash [%s]", string(e))
}
func (art MinerFromANode) GetChildren(hash string, childrenHashes *[]string) (err error) {
for _, block := range ink.GetChildren(hash) {
*childrenHashes = append(*childrenHashes, block2hash(&block))
}
return // TODO: ERROR
}
func (m2m *MinerToMiner) FloodBlockToPeers(block *Block) (err error) {
if len(block.Ops) > 0 {
fmt.Println("Sent block with nonce:", block.Nonce, "ops:", len(block.Ops))
}
// fmt.Println(block.PrevHash, block.Nonce, block.Ops, block.MinedBy)
m2m.HeartbeatNeighbours()
if debugLocks { log.Println("neighbourlock1 locking") }
neighbourlock.RLock()
if debugLocks { log.Println("neighbourlock1 locked") }
for _, neighbour := range ink.neighbours {
var reply bool
go checkError(neighbour.Call("MinerToMiner.ReceiveBlock", &block, &reply))
}
if debugLocks { log.Println("neighbourlock1 unlocking") }
neighbourlock.RUnlock()
if debugLocks { log.Println("neighbourlock1 unlocked") }
return
}
func (m2m *MinerToMiner) FloodOpToPeers(op Operation) (err error) {
// fmt.Println("FLOODOP", op.SVG, op.SVGHash.Hash, len(ink.neighbours))
// fmt.Println(block.PrevHash, block.Nonce, block.Ops, block.MinedBy)
m2m.HeartbeatNeighbours()
if debugLocks { log.Println("neighbourlock1 locking") }
neighbourlock.RLock()
if debugLocks { log.Println("neighbourlock1 locked") }
for _, neighbour := range ink.neighbours {
var reply bool
go checkError(neighbour.Call("MinerToMiner.ReceiveOp", &op, &reply))
}
if debugLocks { log.Println("neighbourlock1 unlocking") }
neighbourlock.RUnlock()
if debugLocks { log.Println("neighbourlock1 unlocked") }
return
}
func (m2m *MinerToMiner) GetHeartbeats(incAddr string, out *string) (err error) {
if debugLocks { log.Println("neighbourlock2 locking") }
neighbourlock.RLock()
if debugLocks { log.Println("neighbourlock2 locked") }
_, ok := ink.neighbours[incAddr]
if debugLocks { log.Println("neighbourlock2 unlocking") }
neighbourlock.RUnlock()
if debugLocks { log.Println("neighbourlock2 unlocked") }
if !ok {
//if neighbour doesn't exist
go func () {
client, err := rpc.Dial("tcp", incAddr)
if !checkError(err) {
fmt.Println("added:", incAddr)
if debugLocks { log.Println("neighbourlock3 locking") }
neighbourlock.Lock()
if debugLocks { log.Println("neighbourlock3 locked") }
ink.neighbours[incAddr] = client
if debugLocks { log.Println("neighbourlock3 unlocking") }
neighbourlock.Unlock()
if debugLocks { log.Println("neighbourlock3 unlocked") }
}
}()
}
*out = "hello i'm online"
return
}
func (m2m *MinerToMiner) FetchBlockChain(i string, blockchain *[]Block) (err error) {
if debugLocks { fmt.Println("locking7") }
maplock.RLock()
if debugLocks { fmt.Println("locked7") }
v := make([]Block, 0, len(blocks))
for _, value := range blocks {
v = append(v, value)
}
*blockchain = v
if debugLocks { fmt.Println("unlocking7") }
maplock.RUnlock()
if debugLocks { fmt.Println("unlocked7") }
return
}
func deleteUnresponsiveNeighbour(neighbourAddr string, neighbourRPC *rpc.Client) (err error) {
var rep string
err = neighbourRPC.Call("MinerToMiner.GetHeartbeats", ink.localAddr.String(), &rep)
if checkError(err) {
fmt.Println("delete:", neighbourAddr)
neighbourlock.Lock()
delete(ink.neighbours, neighbourAddr)
neighbourlock.Unlock()
}
return
}
func (m2m *MinerToMiner) HeartbeatNeighbours() (err error) {
if debugLocks { log.Println("neighbourlock5 locking") }
neighbourlock.RLock()
if debugLocks { log.Println("neighbourlock5 locked") }
for neighbourAddr, neighbourRPC := range ink.neighbours {
go deleteUnresponsiveNeighbour(neighbourAddr, neighbourRPC)
}
if debugLocks { log.Println("neighbourlock5 unlocking") }
neighbourlock.RUnlock()
if debugLocks { log.Println("neighbourlock5 unlocked") }
//give neighbours time to respond
time.Sleep(2 * time.Second)
//if we have good neighbours, return
neighbourlock.RLock()
// fmt.Println("len neighbours, minminers, neighbours: ", len(ink.neighbours), ink.settings.MinNumMinerConnections, ink.neighbours)
if (len(ink.neighbours) >= int(ink.settings.MinNumMinerConnections)) || (len(ink.neighbours) == 0) {
neighbourlock.RUnlock()
return
}
neighbourlock.RUnlock()
//else we get more neighbours
err = miner2server.GetNodes()
return
}
func (m2m MinerToMiner) checkValidationOps() {
if debugLocks { fmt.Println("locking13") }
maplock.RLock()
if debugLocks { fmt.Println("locked13") }
operationsToReAdd := make([]Operation, 0)
blockCopies := make(map[string]Block, 0)
for k, v := range blocks {
blockCopies[k] = v
}
if debugLocks { fmt.Println("unlocking13") }
maplock.RUnlock()
if debugLocks { fmt.Println("unlocked13") }
validationMap := make(map[string]int)
lengthMap := make(map[string]int)
longestChainHash := ink.getLongestChain()
tipOfChain := blockCopies[longestChainHash]
longestChainLength := ink.Length(longestChainHash)
length := longestChainLength
valCount := 0
for tipOfChain.PrevHash != ink.settings.GenesisBlockHash {
for _, op := range tipOfChain.Ops {
if ecdsa.Verify(&ink.key.PublicKey, op.SVGHash.Hash, op.SVGHash.R, op.SVGHash.S) {
validationMap[string(op.SVGHash.Hash)] = valCount
lengthMap[string(op.SVGHash.Hash)] = length
}
}
length -= 1
valCount += 1
tipOfChain = blockCopies[tipOfChain.PrevHash]
}
for {
if len(toValidateOpsCH) == 0 {
break
}
opToCheck := <-toValidateOpsCH
fmt.Println("TESTING:", opToCheck.SVG)
valCount, ok := validationMap[string(opToCheck.SVGHash.Hash)]
length := lengthMap[string(opToCheck.SVGHash.Hash)]
if ok {
if valCount >= int(opToCheck.ValNum) {
validatedOpsCH <- opToCheck
fmt.Println("VAL", valCount, length, opToCheck.ValNum)
} else if length+valCount < longestChainLength {
neverValidatedOpsCH <- opToCheck
fmt.Println("NEVER", valCount, opToCheck.ValNum, length)
} else {
operationsToReAdd = append(operationsToReAdd, opToCheck)
//fmt.Println("OKNO")
}
} else {
operationsToReAdd = append(operationsToReAdd, opToCheck)
// fmt.Println("NO")
}
}
for _, op := range operationsToReAdd {
toValidateOpsCH <- op
}
}
func (m2m *MinerToMiner) ReceiveBlock(block *Block, reply *bool) (err error) {
if len(block.Ops) > 0 {
fmt.Println("Received block with nonce:", block.Nonce, "ops:", len(block.Ops))
}
// fmt.Println(block.PrevHash, block.Nonce, block.Ops, block.MinedBy)
var remoteBlock Block
remoteBlock = *block
difficulty := ink.settings.PoWDifficultyNoOpBlock
if len(block.Ops) != 0 {
difficulty = ink.settings.PoWDifficultyOpBlock
}
if validateNonce(block, difficulty) { // TODO: Only nonce?
// fmt.Println("trying to validate")
hash := block2hash(&remoteBlock)
if debugLocks {
fmt.Println("locking8")
}
maplock.RLock()
if debugLocks {
fmt.Println("locked8")
}
_, exists := blocks[hash]
if debugLocks {
fmt.Println("unlocking8")
}
maplock.RUnlock()
if debugLocks {
fmt.Println("unlocked8")
}
if !exists {
log.Printf("Validated nonce = %s from block = %s", remoteBlock.Nonce, hash)
newBlockCH <- remoteBlock
foundBlockCH <- remoteBlock // reflood block
m2m.checkValidationOps()
}
}
return
}
func (m2m *MinerToMiner) ReceiveOp(op Operation, reply *bool) (err error) {
fmt.Println("Received operation from neighbour:", op.SVGHash.Hash)
newOpCH <- op
//does not have to put into tovalidate as we only keep track of our own
return nil
//does what receiveBlock does for ops
}
type MinerInfo struct {
Address net.Addr
Key ecdsa.PublicKey
}
type MinerSettings struct {
// Hash of the very first (empty) block in the chain.
GenesisBlockHash string `json:"genesis-block-hash"`
// The minimum number of ink miners that an ink miner should be
// connected to.
MinNumMinerConnections uint8 `json:"min-num-miner-connections"`
// Mining ink reward per op and no-op blocks (>= 1)
InkPerOpBlock uint32 `json:"ink-per-op-block"`
InkPerNoOpBlock uint32 `json:"ink-per-no-op-block"`
// Number of milliseconds between heartbeat messages to the server.
HeartBeat uint32 `json:"heartbeat"`
// Proof of work difficulty: number of zeroes in prefix (>=0)
PoWDifficultyOpBlock uint8 `json:"pow-difficulty-op-block"`
PoWDifficultyNoOpBlock uint8 `json:"pow-difficulty-no-op-block"`
}
type MinerNetSettings struct {
MinerSettings
// Canvas settings
CanvasSettings CanvasSettings `json:"canvas-settings"`
}
type CanvasSettings struct {
// Canvas dimensions
CanvasXMax uint32 `json:"canvas-x-max"`
CanvasYMax uint32 `json:"canvas-y-max"`
}
// Register makes RPC Register(localAddr, pubKey) call, and registers settings returned for canvas or returns error
func (m2s *MinerToServer) Register() (err error) {
fmt.Println("localaddr: ", ink.localAddr)
m := &MinerInfo{
Address: ink.localAddr,
Key: ink.key.PublicKey,
}
var settings MinerNetSettings
err = ink.serverClient.Call("RServer.Register", m, &settings)
if checkError(err) {
return
}
log.Println(settings)
ink.settings = settings
return
}
// GetNodes makes RPC GetNodes(pubKey) call, makes a call to ConnectToNeighbour for each returned addr, can return errors
func (m2s *MinerToServer) GetNodes() (err error) {
if debugLocks { log.Println("neighbourlock6 locking") }
neighbourlock.Lock()
if debugLocks { log.Println("neighbourlock6 locked") }
minerAddresses := make([]net.Addr, 0)
err = ink.serverClient.Call("RServer.GetNodes", ink.key.PublicKey, &minerAddresses)
if logGetNodes { fmt.Println("GetNodes: ", minerAddresses) }
for _, addr := range minerAddresses {
_, ok := ink.neighbours[addr.String()]
if !ok {
client, err := rpc.Dial("tcp", addr.String())
if err == nil {
ink.neighbours[addr.String()] = client
fmt.Println("Added neighbour", addr.String())
} else {
fmt.Println(err)
}
}
}
if debugLocks { log.Println("neighbourlock6 unlocking") }
neighbourlock.Unlock()
if debugLocks { log.Println("neighbourlock6 unlocked") }
return
}
// HeartbeatServer makes RPC HearBeat(pubKey) call, changes connected state accordingly which will return different errors for art node requests
func (m2s *MinerToServer) HeartbeatServer() (err error) {
// Create a struct, that mimics all methods provided by interface.
// It is not compulsory, we are doing it here, just to simulate a traditional method call.
var ignored bool
//client.Call("RServer.HeartBeat", nil, &ignored)
err = ink.serverClient.Call("RServer.HeartBeat", ink.key.PublicKey, &ignored)
// fmt.Println("Sent HB:", ignored, err)
return
}
func (ink IMiner) GetBlockChain() (err error) {
if debugLocks { fmt.Println("locking9") }
maplock.Lock()
if debugLocks { fmt.Println("locked9") }
if debugLocks { log.Println("neighbourlock7 locking") }
neighbourlock.RLock()
if debugLocks { log.Println("neighbourlock7 locked") }
for _, neighbour := range ink.neighbours {
blockChain := make([]Block, 0)
err = neighbour.Call("MinerToMiner.FetchBlockChain", "", &blockChain)
for _, block := range blockChain {
blocks[block2hash(&block)] = block
}
}
if debugLocks { log.Println("neighbourlock7 unlocking") }
neighbourlock.RUnlock()
if debugLocks { log.Println("neighbourlock7 unlocked") }
if debugLocks { fmt.Println("unlocking9") }
maplock.Unlock()
if debugLocks { fmt.Println("unlocked9") }
return
}
func (ink IMiner) ProcessNewBlock(b *Block, currentBlock *Block, opQueue []Operation) {
if debugLocks { fmt.Println("locking10") }
maplock.Lock()
if debugLocks { fmt.Println("locked10") }
blocks[block2hash(b)] = *b
if debugLocks { fmt.Println("unlocking10") }
maplock.Unlock()
if debugLocks { fmt.Println("unlocked10") }
longestChainHash := ink.getLongestChain()
// fmt.Println("Switching from:", ink.Length(currentBlock.PrevHash), "to:", ink.Length(longestChainHash))
for _, o := range currentBlock.Ops {
isMined := false
for _, mined := range b.Ops {
if bytes.Equal(o.SVGHash.Hash, mined.SVGHash.Hash) {
isMined = true
}
}
if !isMined {
opQueue = append(opQueue, o)
}
}
*currentBlock = Block{
PrevHash: longestChainHash,
MinedBy: ink.key.PublicKey,
Ops: opQueue,
}
}
func (ink IMiner) ProcessNewOp(op Operation, currentBlock *Block, opQueue []Operation) {
exists := false
for _, o := range opQueue {
if bytes.Equal(op.SVGHash.Hash, o.SVGHash.Hash) {
exists = true
// fmt.Println("EXISTS in queue")
}
}
for _, o := range currentBlock.Ops {
if bytes.Equal(op.SVGHash.Hash, o.SVGHash.Hash) {
exists = true
// fmt.Println("EXISTS in block")
}
}
if !exists {
var newOps []Operation
newOps = append(currentBlock.Ops, opQueue...)
if validateOpsForBlock(append(newOps, op), *currentBlock) {
currentBlock.Ops = append(newOps, op)
var m2m MinerToMiner
m2m.FloodOpToPeers(op)
} else {
currentBlock.Ops = newOps
}
}
//This is how the miner actually handles the new op when it is handed it through a channel by an RPC call from art node OR a flood from neighbour
}
func (ink IMiner) ProcessMinedBlock(currentBlock *Block, opQueue []Operation) {
prevHash := block2hash(currentBlock)
if debugLocks { fmt.Println("locking") }
maplock.Lock()
if debugLocks { fmt.Println("locked") }
blocks[prevHash] = *currentBlock
if debugLocks { fmt.Println("unlocking") }
maplock.Unlock()
if debugLocks { fmt.Println("unlocked") }
//fmt.Println("MINED")
foundBlockCH <- *currentBlock // spit out the found block via channel
*currentBlock = Block{
PrevHash: prevHash,
MinedBy: ink.key.PublicKey,
Ops: opQueue,
}
var m2m MinerToMiner
m2m.checkValidationOps()
}
func (ink IMiner) Mine() (err error) {
var i uint64 = 0
opQueue := make([]Operation, 0)
var currentBlock Block
if len(blocks) == 0 {
currentBlock = getGenesisBlock()
} else {
// mine the longest chain
currentBlock = blocks[ink.getLongestChain()]
}
go func() {
for {
select {
case b := <-newBlockCH:
ink.ProcessNewBlock(&b, ¤tBlock, opQueue)
opQueue = make([]Operation, 0)
i = 0
case o := <-newOpCH:
ink.ProcessNewOp(o, ¤tBlock, opQueue)
opQueue = make([]Operation, 0)
i = 0
default:
i++
if i % 500 == 0 && len(currentBlock.Ops) > 0 {
fmt.Println(i, currentBlock.PrevHash, block2hash(¤tBlock), len(currentBlock.Ops))
}
if len(currentBlock.Ops) == 0 {
//time.Sleep(time.Microsecond * 10)
}
difficulty := ink.settings.PoWDifficultyNoOpBlock
if len(currentBlock.Ops) != 0 {
difficulty = ink.settings.PoWDifficultyOpBlock
}
currentBlock.Nonce = strconv.FormatUint(i, 10)
if validateBlock(¤tBlock, difficulty) {
ink.ProcessMinedBlock(¤tBlock, opQueue)
opQueue = make([]Operation, 0)
i = 0
}
}
}
}()
return nil
}
func (ink IMiner) GetGenesisBlock() (genesis Block) {
if debugLocks { fmt.Println("locking2") }
maplock.RLock()
if debugLocks { fmt.Println("locked2") }
genesisBlock := blocks[ink.settings.GenesisBlockHash]
if debugLocks { fmt.Println("unlocking2") }
maplock.RUnlock()
if debugLocks { fmt.Println("unlocked2") }
return genesisBlock
}
func (ink IMiner) GetChildren(hash string) (children []Block) {
if debugLocks { fmt.Println("locking3") }
maplock.RLock()
if debugLocks { fmt.Println("locked3") }
children = make([]Block, 0)
for _, block := range blocks {
if block.PrevHash == hash {
children = append(children, block)
}
}
if debugLocks { fmt.Println("unlocking3") }
maplock.RUnlock()
if debugLocks { fmt.Println("unlocked3") }
return
}
func (ink IMiner) getBlockChainHeads() (heads []Block) {
if debugLocks { fmt.Println("locking4") }
maplock.RLock()
if debugLocks { fmt.Println("locked4") }
possibilities := make(map[string]Block)
for k, v := range blocks {
possibilities[k] = v
}
for _, block := range blocks {
delete(possibilities, block.PrevHash)
}
if debugLocks { fmt.Println("unlocking4") }
maplock.RUnlock()
if debugLocks { fmt.Println("unlocked4") }
for _, v := range possibilities {
heads = append(heads, v)
}
return
}
func (ink IMiner) Length(hash string) (len int) {
return ink.LengthFromTo(hash, ink.settings.GenesisBlockHash)
}
func (ink IMiner) LengthFromTo(from string, to string) (length int) {
if debugLocks { fmt.Println("locking11") }
maplock.RLock()
if debugLocks { fmt.Println("locked11") }
for from != to {
length += 1
block, ok := blocks[from]
if !ok {
length = 0
break
}
from = block.PrevHash
}
if debugLocks { fmt.Println("unlocking11") }
maplock.RUnlock()
if debugLocks { fmt.Println("unlocked11") }
return
}
func (ink IMiner) getLongestChain() (hash string){
longest := 0
hash = ink.settings.GenesisBlockHash // hash of the genesis block
for _, head := range ink.getBlockChainHeads() {
bhash := block2hash(&head)
length := ink.Length(bhash)
if length > longest {
longest = length
hash = bhash
} else if length == longest {
// equal length chains: pick the larger hash
if bhash > hash {
hash = bhash
}
}
}
return
}
func (ink IMiner) ValidationCount(hash string) (validationCount int) {
for _, head := range ink.getBlockChainHeads() {
headLength := ink.LengthFromTo(block2hash(&head), hash)
if headLength > validationCount {
validationCount = headLength
}
}
return
}
var ink IMiner
var miner2server MinerToServer
var miner2miner MinerToMiner
var blocks map[string]Block
var newOpCH (chan Operation)
var newBlockCH (chan Block)
var foundBlockCH (chan Block)
var foundOpCH (chan Operation)
var validatedOpsCH (chan Operation)
var toValidateOpsCH (chan Operation)
var neverValidatedOpsCH (chan Operation)
var maplock sync.RWMutex
var neighbourlock sync.RWMutex
func listenForMinerToMinerRPC(address string) net.Addr {
server := rpc.NewServer()
server.Register(&MinerToMiner{})
l, _ := net.Listen("tcp", address)
go func() {
for {
conn, _ := l.Accept()
go server.ServeConn(conn)
}
}()
return l.Addr()
}
func registerGobAndCreateChannels() {
gob.Register(&net.TCPAddr{})
gob.Register(&elliptic.CurveParams{})
gob.Register(&MinerInfo{})
gob.Register(&[]Block{})
gob.Register(ecdsa.PrivateKey{})
gob.Register(Operation{})
blocks = make(map[string]Block)
newOpCH = make(chan Operation, math.MaxUint8)
// big enough to handle one op from each miner
foundOpCH = make(chan Operation, math.MaxUint16)
newBlockCH = make(chan Block, math.MaxUint8)
foundBlockCH = make(chan Block, math.MaxUint8)
validatedOpsCH = make(chan Operation, math.MaxUint8)
toValidateOpsCH = make(chan Operation, math.MaxUint8)
neverValidatedOpsCH = make(chan Operation, math.MaxUint8)
}
func openRPCToServer(serverIp string) (client *rpc.Client, err error) {
ipPort := flag.String("i", serverIp, "RPC server ip:port")
return rpc.Dial("tcp", *ipPort)
}
func getGenesisBlock() (Block) {
return Block{
PrevHash: ink.settings.GenesisBlockHash,
Nonce: "1337",
MinedBy: ecdsa.PublicKey{},
}
}
func main() {
if len(os.Args) != 4 {
fmt.Println("Usage: ink-miner.go [local ip:port for miner rpc] [local ip:port for art rpc] [server ip:port]")
os.Exit(1)
}
localIpMinerRPC := os.Args[1]
localIpArtRPC := os.Args[2]
serverIp := os.Args[3]
registerGobAndCreateChannels()
server, err := openRPCToServer(serverIp)
checkError(err)
priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
fmt.Println(err)
}
ink = IMiner{
serverClient: server,
key: *priv,
localAddr: listenForMinerToMinerRPC(localIpMinerRPC),
neighbours: make(map[string]*rpc.Client),
}
// Register with server
miner2server.Register()
checkError(miner2server.GetNodes())
checkError(ink.GetBlockChain())
// Starts the flood routine that floods new blocks
startFloodListener()
// Starts the routine that waits for validated ops
startValidationListener()
// Heartbeat server
heartbeatTheServer()
// Start mining
checkError(ink.Mine())
// Listen incoming RPC calls from artnodes
go listenForArtNodes(localIpArtRPC)
defer clearMinerKeyFile()
// Heartbeat your neighbours s.t. you know when you get some.
checkError(miner2miner.HeartbeatNeighbours())
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
for _ = range c {
dumpBlockchain()
clearMinerKeyFile()
os.Exit(0)
} // This is blocking. Do not add anything after this.
}
func startValidationListener() {
go func() {
for {
var m2m MinerToMiner
m2m.checkValidationOps()
time.Sleep(time.Millisecond * 100)
}
}()
}
func startFloodListener() {
go func() {
for {
minedBlock := <-foundBlockCH
miner2miner.FloodBlockToPeers(&minedBlock)
}
}()
}
func heartbeatTheServer() {
go func() {
for {
miner2server.HeartbeatServer()
time.Sleep(time.Millisecond * 5)
}
}()
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// END OF ?, START OF ART2MINER IMLEMENTATION //
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
type RMiner int
func (m *RMiner) OpenCanvas(keyHash [16]byte, reply *CanvasSettings) error {
fmt.Println("New ArtNode connecting")
if hashPrivateKey(ink.key) != keyHash {
return errors.New("Miner: The key you are connecting with is not correct")
}
*reply = ink.settings.CanvasSettings // <-- should have queried the server first
//*reply = CanvasSettings{1024, 1024} // <-- for now..
return nil
}
func (m *RMiner) ReceiveNewOp(op Operation, reply *string) error {
if !ecdsa.Verify(&ink.key.PublicKey, op.SVGHash.Hash, op.SVGHash.R, op.SVGHash.S) {
return errors.New("Invalid signature")
}
newOpCH <- op
toValidateOpsCH <- op
fmt.Println("Received op:", op.SVG, "Ops to be validated:", len(toValidateOpsCH))
for {
select {
case validatedOp := <- validatedOpsCH:
if bytes.Equal(validatedOp.SVGHash.Hash, op.SVGHash.Hash) {
return nil
} else {
validatedOpsCH <- validatedOp
}
case neverValidatedOp := <- neverValidatedOpsCH:
if bytes.Equal(neverValidatedOp.SVGHash.Hash, op.SVGHash.Hash) {
fmt.Println("Re-added op")
newOpCH <- op
toValidateOpsCH <- op
} else {
neverValidatedOpsCH <- neverValidatedOp
}
}
}
fmt.Println("Added op:", op.SVG)
return nil
}
func (m *RMiner) getInkForBlock(publicKey ecdsa.PublicKey, block Block, blockHash string) uint32 {
if block.MinedBy == ink.key.PublicKey {
allOpsValidated := true
validateNum := uint8(ink.ValidationCount(blockHash))
for _, op := range block.Ops {
if ecdsa.Verify(&publicKey, op.SVGHash.Hash, op.SVGHash.R, op.SVGHash.S) && validateNum < op.ValNum {
allOpsValidated = false
}
}
if !allOpsValidated {
return 0
}
if len(block.Ops) > 0 {
return ink.settings.InkPerOpBlock
} else {
return ink.settings.InkPerNoOpBlock
}
}
return 0
}
func (m *RMiner) useInkForBlock(publicKey ecdsa.PublicKey, block Block) uint32 {
var total uint32 = 0
p := blockartlib.NewSVGParser()
for _, op := range block.Ops {
if !ecdsa.Verify(&publicKey, op.SVGHash.Hash, op.SVGHash.R, op.SVGHash.S) {
continue
}
var err error
if op.Delete {
op, err = GetOperation(op.SVG)
}
shape, err := p.ParseXMLString(op.SVG)
if checkError(err) {
continue
}
if op.Delete {
total += shape.Area()
} else {
total -= shape.Area()
}
}
return total