-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminer.go
1523 lines (1404 loc) · 46.9 KB
/
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
/*
Implements a miner network
Usage:
$ go run client.go [local UDP ip:port] [local TCP ip:port] [aserver UDP ip:port]
Example:
$ go run client.go 127.0.0.1:2020 127.0.0.1:3030 127.0.0.1:7070
*/
package main
import (
"crypto/md5"
"encoding/gob"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"math"
"net"
"net/rpc"
"os"
"sync"
"time"
"github.com/DistributedClocks/GoVector/govec"
"github.com/google/go-cmp/cmp"
"github.ugrad.cs.ubc.ca/CPSC416-2018W-T1/P1-i8b0b-e8y0b/rfslib"
)
func init() {
gob.Register(rfslib.OperationRecord{})
gob.Register(OPBlock{})
gob.Register(NOPBlock{})
gob.Register(GenesisBlock{})
}
// NOPBlockType is ...
const (
NOPBlockType = iota
OPBlockType
)
// BlockPacket is ...
type BlockPacket struct {
BlockType int
BlockData []byte
}
// Block is the interface for GenesisBlock, NOPBlock and OPBlock
type Block interface {
hash() string
prevHash() string
minerID() string
// getHeight() (uint32, error)
}
// GenesisBlock is the first block in this blockchain
type GenesisBlock struct {
Hash string // The genesis (first) block MD5 hash for this blockchain
}
func (gblock GenesisBlock) hash() string {
return gblock.Hash
}
func (gblock GenesisBlock) prevHash() string {
return gblock.Hash
}
func (gblock GenesisBlock) minerID() string {
return "NoSuchGenesisBlockMiner"
}
// NOPBlock is a No-OP Block
type NOPBlock struct {
PrevHash string // A hash of the previous block in the chain (prev-hash)
Nonce uint32 // A 32-bit unsigned integer nonce (nonce)
MinerID string // The identifier of the miner that computed this block (block-minerID)
MinerBalance uint32 // The updated balance of the miner that computed this block
}
func (nopblock NOPBlock) hash() string {
h := md5.New()
h.Write([]byte(fmt.Sprintf("%v", nopblock)))
return hex.EncodeToString(h.Sum(nil))
}
func (nopblock NOPBlock) prevHash() string {
return nopblock.PrevHash
}
func (nopblock NOPBlock) minerID() string {
return nopblock.MinerID
}
// OPBlock is a OP Block with non-empty Records
type OPBlock struct {
PrevHash string // A hash of the previous block in the chain (prev-hash)
Records []rfslib.OperationRecord // An ordered set of operation records
Nonce uint32 // A 32-bit unsigned integer nonce (nonce)
MinerID string // The identifier of the miner that computed this block (block-minerID)
MinerBalance uint32 // The updated balance of the miner that computed this block
}
func (opblock OPBlock) hash() string {
h := md5.New()
h.Write([]byte(fmt.Sprintf("%v", opblock)))
return hex.EncodeToString(h.Sum(nil))
}
func (opblock OPBlock) prevHash() string {
return opblock.PrevHash
}
func (opblock OPBlock) minerID() string {
return opblock.MinerID
}
// PeerMinerInfo is ...
type PeerMinerInfo struct {
IncomingMinersAddr string
MinerID string
}
// Miner mines blocks.
type Miner struct {
// These would not change once initialized
Settings
Logger *govec.GoLog // The GoVector Logger
GoVecOptions govec.GoLogOptions // The GoVector log options
GeneratedBlocksChan chan Block // Channel of generated blocks
StopMiningChan chan string // Channel that stops computeOPBlock or computeNOPBlock
OperationRecordChan chan rfslib.OperationRecord // Channel of valid operation records received from other miners
// No need to initialize :)
chain sync.Map // {hash: Block} All the blocks in the network
chainTips sync.Map // {hash: height of the fork} The collection of the tails of all valid forks
peerMiners sync.Map // {minerID: *rpc.Client} The connected peer miners (including these newly joined)
}
// Settings contains all miner settings and is loaded through
// a configuration file. See:
// https://www.cs.ubc.ca/~bestchai/teaching/cs416_2018w1/project1/config.json.
type Settings struct {
// The ID of this miner (max 16 characters).
MinerID string
// An array of remote IP:port addresses, one per peer miner that this miner should
// connect to (using the OutgoingMinersIP below).
PeerMinersAddrs []string
// The local IP:port where the miner should expect other miners to connect to it
// (address it should listen on for connections from miners).
IncomingMinersAddr string
// The local IP that the miner should use to connect to peer miners.
OutgoingMinersIP string
// The local IP:port where this miner should expect to receive connections
// from RFS clients (address it should listen on for connections from clients)
IncomingClientsAddr string
// The number of record coins mined for an op block.
MinedCoinsPerOpBlock uint8
// The number of record coins mined for a no-op block.
MinedCoinsPerNoOpBlock uint8
// The number of record coins charged for creating a file.
NumCoinsPerFileCreate uint8
// Time in milliseconds, the minimum time between op block mining.
GenOpBlockTimeout uint8
// The genesis (first) block MD5 hash for this blockchain.
GenesisBlockHash string
// The op block difficulty (proof of work setting: number of zeroes).
PowPerOpBlock uint8
// The no-op block difficulty (proof of work setting: number of zeroes).
PowPerNoOpBlock uint8
// The number of confirmations for a create file operation
// (the number of blocks that must follow the block containing a create file operation
// along longest chain before the CreateFile call can return successfully).
ConfirmsPerFileCreate uint8
// The number of confirmations for an append operation (the number of blocks
// that must follow the block containing an append operation along longest chain
// before the AppendRec call can return successfully). Note that this append confirm
// number will always be set to be larger than the create confirm number (above).
ConfirmsPerFileAppend uint8
}
// ClientAPI is the set of RPC calls provided to RFS
type ClientAPI struct {
miner *Miner // A reference to the current miner
listenAddr string // The local IP:port where this miner should expect to receive connections from RFS clients
}
// MinerAPI is the set of RPC calls provided to other miners
type MinerAPI struct {
miner *Miner // A reference to the current miner
listenAddr string // The local IP:port where the miner should expect other miners to connect to it
}
// GetChainTips RPC provides the active starting point of the current blockchain
// parameter arg is optional and not being used at all
func (mapi *MinerAPI) GetChainTips(caller string, reply *map[string]int) error {
log.Println("MinerAPI.GetChainTips got a call from " + caller)
dumpedChainTips := make(map[string]int)
mapi.miner.chainTips.Range(func(blockHash, height interface{}) bool {
dumpedChainTips[blockHash.(string)] = height.(int)
return true
})
*reply = dumpedChainTips
return nil
}
func loadBlock(packet BlockPacket) (Block, error) {
var block Block
switch packet.BlockType {
case OPBlockType:
var opBlock OPBlock
err := json.Unmarshal(packet.BlockData, &opBlock)
if err != nil {
return block, err
}
// log.Println("loadBlock: Unmarshalled a OPBlock", opBlock.hash())
block = opBlock
case NOPBlockType:
var nopBlock NOPBlock
err := json.Unmarshal(packet.BlockData, &nopBlock)
if err != nil {
return block, err
}
// log.Println("loadBlock: Unmarshalled a NOPBlock", nopBlock.hash())
block = nopBlock
default:
return block, errors.New("SubmitBlock: block type in packet not supported")
}
return block, nil
}
func dumpBlock(block Block, packet *BlockPacket) error {
// var packet BlockPacket
var err error
switch t := block.(type) {
case GenesisBlock:
return errors.New("loadBlock: should not load a GenesisBlock")
default:
return errors.New("loadBlock: block type not recognized")
case OPBlock:
packet.BlockType = OPBlockType
packet.BlockData, err = json.Marshal(t)
if err != nil {
return err
}
case NOPBlock:
packet.BlockType = NOPBlockType
packet.BlockData, err = json.Marshal(t)
if err != nil {
return err
}
}
return nil
}
// GetBlock RPC gets a block with a particular header hash from the local blockchain map
func (mapi *MinerAPI) GetBlock(headerHash string, packet *BlockPacket) error {
block, exists := mapi.miner.chain.Load(headerHash)
if exists {
err := dumpBlock(block.(Block), packet)
if err != nil {
return err
}
return nil
}
return errors.New("The requested block does not exist in the local blockchain:" + mapi.miner.MinerID)
}
func (m *Miner) addNode(minerInfo PeerMinerInfo) error {
log.Println("addNode: dialing", minerInfo.IncomingMinersAddr, "to", minerInfo.MinerID)
// client, err := jsonrpc.Dial("tcp", minerInfo.IncomingMinersAddr)
client, err := rpc.Dial("tcp", minerInfo.IncomingMinersAddr)
// client, err := vrpc.RPCDial("tcp", minerInfo.IncomingMinersAddr, m.Logger, m.GoVecOptions)
if err != nil {
log.Fatalln("addNode: ", err)
return err
}
m.peerMiners.Store(minerInfo.MinerID, client)
return nil
}
// AddNode RPC adds the remote node to its own network
func (mapi *MinerAPI) AddNode(minerInfo PeerMinerInfo, received *bool) error {
*received = true
if err := mapi.miner.addNode(minerInfo); err != nil {
return err
}
return nil
}
// GetPeerInfo RPC returns the current miner info
func (mapi *MinerAPI) GetPeerInfo(caller string, minerID *string) error {
log.Println("MinerAPI.GetPeerInfo got request from", caller)
*minerID = mapi.miner.MinerID
return nil
}
// validateRecordSemantics checks that each operation does not violate RFS semantics
// (e.g., a record is not mutated or inserted into the middled of an rfs file).
func (m *Miner) validateRecordSemantics(block Block, opRecord rfslib.OperationRecord) error {
currentRecordNum := opRecord.RecordNum
funcName := "validateRecordSemantics: "
for block.hash() != block.prevHash() {
prevBlock, ok := m.chain.Load(block.prevHash())
if !ok {
return errors.New(funcName + "encountered an orphaned block when checking RFS semantics")
}
switch t := block.(type) {
case NOPBlock:
break
case OPBlock:
switch opRecord.OperationType {
case "delete":
break
case "create":
for _, prevRecord := range t.Records {
if prevRecord.FileName == opRecord.FileName {
return errors.New(funcName + "file name " + opRecord.FileName + " already exists in this chain")
}
}
case "append":
for _, prevRecord := range t.Records {
log.Println("encountered", prevRecord)
if prevRecord.FileName != opRecord.FileName {
continue
}
if currentRecordNum == prevRecord.RecordNum+1 {
currentRecordNum = prevRecord.RecordNum
if currentRecordNum == 1 {
// TODO: decide the initial record num for append
return nil
}
} else {
return fmt.Errorf("toAppend %d tail %d (inserted into the middle)", currentRecordNum, prevRecord.RecordNum)
// errors.New(funcName + "encountered (inserted into the middled of an rfs file)")
}
}
default:
return errors.New(funcName + "encountered an invalid OperationRecord Type")
}
default:
return errors.New(funcName + "encountered an invalid intermediate block " + block.hash())
}
block = prevBlock.(Block)
}
return nil
}
// validateBlock returns true if the given block is valid, false otherwise
func (m *Miner) validateBlock(block Block) error {
// Block validations
switch t := block.(type) {
default:
return errors.New("validateBlock: invalid Block Type " + block.hash())
case OPBlock:
if validateNonce(t, m.PowPerOpBlock) == false {
return errors.New("validateBlock: OPBlock " + t.hash() + " does not have the right difficulty")
}
// Check that the previous block hash points to a legal, previously generated, block.
prevBlock, prevBlockExists := m.chain.Load(t.PrevHash)
if !prevBlockExists {
err := m.requestPreviousBlocks(t.PrevHash)
if err != nil {
return errors.New("validateBlock: OPBlock " + t.hash() + " does not have a previous block")
}
prevBlock, prevBlockExists = m.chain.Load(t.PrevHash)
if !prevBlockExists {
return errors.New("validateBlock: OPBlock " + t.hash() + " belongs to an orphaned chain :(")
}
}
log.Println("validateBlock: OPBlock has prevHash", t.PrevHash)
prevChainTip := prevBlock.(Block)
// Operation validations:
// Check that each operation in the block is associated with a miner ID that has enough record coins to pay for the operation
// (i.e., the number of record coins associated with the minerID must have sufficient balance to 'pay' for the operation).
balanceRequiredMap := make(map[string]uint32)
for _, opRecord := range t.Records {
if opRecord.OperationType == "create" {
balanceRequiredMap[opRecord.MinerID] += uint32(m.NumCoinsPerFileCreate)
} else if opRecord.OperationType == "append" {
balanceRequiredMap[opRecord.MinerID]++
}
}
for minerID, balanceRequired := range balanceRequiredMap {
balance, err := m.getBalance(t, minerID)
if err != nil {
return errors.New("validateBlock: checking balanceRequired:" + err.Error())
} else if balance < balanceRequired {
return errors.New("validateBlock: the miner" + minerID + "of the OperationRecord does not have enough balance")
}
}
// Check that each operation does not violate RFS semantics
// (e.g., a record is not mutated or inserted into the middled of an rfs file).
for _, opRecord := range t.Records {
if err := m.validateRecordSemantics(prevChainTip, opRecord); err != nil {
return err
}
}
break
case NOPBlock:
if validateNonce(t, m.PowPerNoOpBlock) == false {
log.Println(t.hash(), "PowPerNoOpBlock", m.PowPerNoOpBlock)
return fmt.Errorf("validateBlock: NOPBlock %s does not have the right difficulty %d", t.hash(), m.PowPerNoOpBlock)
}
// Check that the previous block hash points to a legal, previously generated, block.
if _, ok := m.chain.Load(t.PrevHash); ok {
// fmt.Println("validateBlock: the previous block of this NOPBlock is:", t.prevHash())
} else {
err := m.requestPreviousBlocks(t.PrevHash)
if err != nil {
return fmt.Errorf("validateBlock: NOPBlock %s does not have a previous block %s", t.hash(), t.prevHash())
}
}
break
case GenesisBlock:
if _, ok := m.chain.Load(m.GenesisBlockHash); ok {
return errors.New("validateBlock: a GenesisBlock with the same hash already existed")
}
loaded := false
m.chainTips.Range(func(key, value interface{}) bool {
loaded = true
return false
})
if loaded {
return errors.New("validateBlock: the local chain already contains a GenesisBlock")
}
}
// check duplicate blocks (currently done in addBlock)
/*if _, ok := m.chain.Load(block.hash()); ok {
return errors.New("a block with the same hash already existed")
}*/
return nil
}
// SubmitRecord RPC from MinerAPI submits rfslib.OperationRecord to the miner network
// if the mined coins are sufficient to cover the cost
func (mapi *MinerAPI) SubmitRecord(newOpRecord *rfslib.OperationRecord, nextRecordNum *uint16) error {
funcName := "MinerAPI.SubmitRecord: "
block := mapi.miner.getBlockFromLongestChain()
log.Println(funcName, "recv", newOpRecord.OperationType, newOpRecord.FileName, newOpRecord.RecordData)
balance, err := mapi.miner.getBalance(block, newOpRecord.MinerID)
if err != nil {
return errors.New(funcName + "checking balanceRequired:" + err.Error())
}
err = mapi.miner.validateRecordSemantics(block, *newOpRecord)
if err != nil {
log.Println(funcName, "err", err)
return errors.New(funcName + err.Error())
}
switch newOpRecord.OperationType {
case "delete":
break
case "create":
if uint32(mapi.miner.NumCoinsPerFileCreate) > balance {
return errors.New(funcName + "the current balance is not enough to cover create")
}
case "append":
if balance < 1 {
return errors.New(funcName + "the current balance is not enough to cover append")
}
}
log.Println(funcName, "chan", newOpRecord.OperationType, newOpRecord.FileName, newOpRecord.RecordData)
mapi.miner.OperationRecordChan <- *newOpRecord
return nil
}
// ReadRecord RPC (call from ClientAPI) makes a best effort read and returns the closet matching OperationRecord
// it only returns an error if the given file cannot be found or if it encounters an internal error
func (capi *ClientAPI) ReadRecord(recordInfo *rfslib.OperationRecord, minerRes *rfslib.MinerRes) error {
fname := recordInfo.FileName
recordNum := recordInfo.RecordNum
opRecord, err := capi.miner.readRecord(fname, recordNum)
if err != nil {
if _, ok := err.(rfslib.FileDoesNotExistError); ok {
*minerRes = rfslib.MinerRes{
HasErr: true,
Error: rfslib.FileDoesNotExist,
}
return nil
}
return err
}
*minerRes = rfslib.MinerRes{
Data: opRecord,
HasErr: false,
}
log.Printf("%v\n", *minerRes)
return nil
}
// SubmitRecord RPC (call from ClientAPI) submits operationRecord to the miner network
// if the mined coins are sufficient to cover the cost
func (capi *ClientAPI) SubmitRecord(newOpRecord *rfslib.OperationRecord, res *rfslib.MinerRes) error {
block := capi.miner.getBlockFromLongestChain()
funcName := "ClientAPI.SubmitRecord: "
log.Println(funcName, "recv", newOpRecord.OperationType, newOpRecord.FileName, newOpRecord.RecordData)
balance, err := capi.miner.getBalance(block, capi.miner.MinerID)
if err != nil {
return errors.New(funcName + "checking balanceRequired:" + err.Error())
}
switch newOpRecord.OperationType {
case "delete":
break
case "create":
if uint32(capi.miner.NumCoinsPerFileCreate) > balance {
*res = rfslib.MinerRes{
HasErr: true,
Error: rfslib.Insufficient,
}
}
case "append":
if balance < 1 {
*res = rfslib.MinerRes{
HasErr: true,
Error: rfslib.Insufficient,
}
}
// We assume that the previous records are confirmed before a client append a new one
mostRecentRecord, err := capi.miner.readRecord(newOpRecord.FileName, 65535)
if err != nil {
*res = rfslib.MinerRes{
HasErr: true,
Error: rfslib.FileDoesNotExist,
}
}
if mostRecentRecord.RecordNum == 65535 {
*res = rfslib.MinerRes{
HasErr: true,
Error: rfslib.FileMaxLenReached,
}
}
if newOpRecord.RecordNum == 0 && newOpRecord.OperationType == "append" {
newOpRecord.RecordNum = mostRecentRecord.RecordNum + 1
log.Println(funcName, "assigning new RecordNum =", newOpRecord.RecordNum)
}
}
newOpRecord.MinerID = capi.miner.MinerID
log.Println("chan < submitrecord ")
capi.miner.OperationRecordChan <- *newOpRecord
*res = rfslib.MinerRes{
HasErr: false,
Data: newOpRecord.RecordNum,
}
return nil
}
func (m *Miner) getOperationRecordHeight(block Block, srcRecord rfslib.OperationRecord) (int, error) {
confirmedBlocksNum := 0
funcName := "getOperationRecordHeight: "
for block.hash() != block.prevHash() {
switch t := block.(type) {
default:
return -1, errors.New(funcName + "invalid Block Type")
case OPBlock:
// log.Println(funcName, "OPBlock", block.hash())
for _, dstRecord := range t.Records {
log.Println(funcName, confirmedBlocksNum, srcRecord.MinerID, srcRecord.OperationType, srcRecord.RecordNum)
log.Println(funcName, confirmedBlocksNum, dstRecord.MinerID, dstRecord.OperationType, dstRecord.RecordNum)
if cmp.Equal(srcRecord, dstRecord) {
log.Println(funcName, confirmedBlocksNum, dstRecord.FileName, ":", dstRecord.RecordNum)
return confirmedBlocksNum, nil
}
}
confirmedBlocksNum++
case NOPBlock:
confirmedBlocksNum++
}
// Check that the previous block hash points to a legal, previously generated, block.
prevBlock, exists := m.chain.Load(block.prevHash())
if !exists {
return -1, errors.New(funcName + "block" + block.hash() + "does not have a valid prevBlock")
}
block = prevBlock.(Block)
}
return -1, fmt.Errorf("%s Record %s %d cannot be found", funcName, srcRecord.FileName, srcRecord.RecordNum)
}
// ConfirmOperation RPC should be invoked by the RFS Client
// upon succesfully confimation it returns nil
func (capi *ClientAPI) ConfirmOperation(operationRecord *rfslib.OperationRecord, minerRes *rfslib.MinerRes) error {
funcName := "ClientAPI.ConfirmOperation: "
// log.Println(funcName, operationRecord.FileName, operationRecord.RecordNum)
block := capi.miner.getBlockFromLongestChain()
operationRecord.MinerID = capi.miner.MinerID
confirmedBlocksNum, err := capi.miner.getOperationRecordHeight(block, *operationRecord)
if err != nil {
log.Println(funcName, err)
return err
}
log.Println(funcName, confirmedBlocksNum, operationRecord)
switch operationRecord.OperationType {
default:
return errors.New("Operation Type not recognized")
case "delete":
return errors.New("Delete not supported")
case "create":
if int(capi.miner.ConfirmsPerFileCreate) > confirmedBlocksNum {
*minerRes = rfslib.MinerRes{
HasErr: true,
Error: rfslib.NotConfirmed,
}
}
case "append":
if int(capi.miner.ConfirmsPerFileAppend) > confirmedBlocksNum {
*minerRes = rfslib.MinerRes{
HasErr: true,
Error: rfslib.NotConfirmed,
}
}
}
return nil
}
// GetBalance RPC call should be invoked by the RFS Client and does not take an input
// it returns the current balance of the longest chain of the miner being quried
func (capi *ClientAPI) GetBalance(caller string, currentBalance *uint32) error {
log.Println("MinerAPI.GetBalance got a call from " + caller)
bestChainTip := capi.miner.getBlockFromLongestChain()
var err error
*currentBalance, err = capi.miner.getBalance(bestChainTip, capi.miner.MinerID)
return err
}
func (m *Miner) listFiles() ([]string, error) {
fnamesMap := make(map[string]bool)
fnamesSlice := make([]string, 0, 100)
confirmedBlocksNum := 0
block := m.getBlockFromLongestChain()
funcName := "listFiles: "
for block.hash() != block.prevHash() {
prevBlock, ok := m.chain.Load(block.prevHash())
if !ok {
return fnamesSlice, errors.New(funcName + "encountered an orphaned block" + block.hash())
}
confirmedBlocksNum++
switch t := block.(type) {
case NOPBlock:
break
case OPBlock:
for _, opRecord := range t.Records {
if opRecord.OperationType == "create" && int(m.ConfirmsPerFileCreate) < confirmedBlocksNum {
fnamesMap[opRecord.FileName] = true
}
}
default:
return fnamesSlice, errors.New(funcName + "encountered an invalid intermediate block" + block.hash())
}
block = prevBlock.(Block)
}
for fname := range fnamesMap {
fnamesSlice = append(fnamesSlice, fname)
}
return fnamesSlice, nil
}
func (m *Miner) countRecords(fname string) (uint16, error) {
// recordNum := 0
block := m.getBlockFromLongestChain()
confirmedBlocksNum := 0
for block.hash() != block.prevHash() {
prevBlock, ok := m.chain.Load(block.prevHash())
if !ok {
return 0, errors.New("countRecords: encountered an orphaned block when counting records")
}
confirmedBlocksNum++
switch t := block.(type) {
case NOPBlock:
break
case OPBlock:
for _, opRecord := range t.Records {
if opRecord.FileName == fname {
switch opRecord.OperationType {
default:
return 0, errors.New("countRecords: operation Type not recognized")
case "delete":
return 0, errors.New("countRecords: delete not supported")
case "create":
if int(m.ConfirmsPerFileCreate) < confirmedBlocksNum {
return 0, nil
}
return 0, nil
case "append":
if int(m.ConfirmsPerFileAppend) < confirmedBlocksNum {
return opRecord.RecordNum, nil
}
return 0, nil
}
}
}
default:
return 0, errors.New("countRecords: encountered an invalid intermediate block")
}
block = prevBlock.(Block)
}
return 0, rfslib.FileDoesNotExistError(fmt.Sprintf("miner with id %s could not find file %s\n", m.MinerID, fname))
}
// hasRecord returns if the closet unconfirmed matching record exists
func (m *Miner) hasRecord(toBeFound rfslib.OperationRecord) bool {
var confirmedBlocksNum, requiredBlocksNum uint8
switch toBeFound.OperationType {
case "append":
requiredBlocksNum = m.ConfirmsPerFileAppend
case "create":
requiredBlocksNum = m.ConfirmsPerFileCreate
default:
break
}
block := m.getBlockFromLongestChain()
funcName := "hasRecord: "
for block.hash() != block.prevHash() {
prevBlock, ok := m.chain.Load(block.prevHash())
if !ok {
log.Fatalln(funcName, "encountered an orphaned block")
return false
}
confirmedBlocksNum++
if confirmedBlocksNum < requiredBlocksNum {
block = prevBlock.(Block)
continue
}
switch t := block.(type) {
case NOPBlock:
break
case OPBlock:
for _, currentRecord := range t.Records {
if currentRecord.FileName == toBeFound.FileName {
switch currentRecord.OperationType {
case "create":
// if we can find the header of the file and the header is confirmed then we are set
// (observation: if we are here then the appended blocks are not confirmed yet)
if toBeFound.RecordNum == 0 {
return true
}
case "append":
// if we can find the tail record of the file
log.Println("toBeFound", toBeFound.RecordNum, currentRecord.RecordNum, requiredBlocksNum)
if toBeFound.RecordNum <= currentRecord.RecordNum {
return true
}
default:
break
}
}
}
default:
log.Fatalln(funcName, "encountered an unreognized block")
return false
}
block = prevBlock.(Block)
}
return false
}
// readRecord returns the closet matching record to the request record if file can be found and error otherwise
// (will make the best effort and parameter recordNum will be greater than or equals to that of returned record)
func (m *Miner) readRecord(fname string, recordNum uint16) (rfslib.OperationRecord, error) {
block := m.getBlockFromLongestChain()
var invalidOpRecord rfslib.OperationRecord
funcName := "readRecord: "
confirmedBlocksNum := 0
for block.hash() != block.prevHash() {
prevBlock, ok := m.chain.Load(block.prevHash())
if !ok {
return invalidOpRecord, errors.New(funcName + "encountered an orphaned block when counting records")
}
confirmedBlocksNum++
switch t := block.(type) {
case NOPBlock:
break
case OPBlock:
for _, opRecord := range t.Records {
if opRecord.FileName == fname {
switch opRecord.OperationType {
default:
break
case "create":
// if we can find the header of the file and the header is confirmed...
// (observation: if we are here then the appended blocks are not confirmed yet)
if opRecord.FileName == fname && int(m.ConfirmsPerFileCreate) < confirmedBlocksNum {
return opRecord, nil
}
case "append":
log.Println(opRecord.FileName, opRecord.RecordNum, opRecord.OperationType)
// if we can find the tail record of the file
if opRecord.FileName == fname && int(m.ConfirmsPerFileAppend) < confirmedBlocksNum {
log.Println("readRecord: requesting", recordNum, "has", opRecord.RecordNum)
if recordNum >= opRecord.RecordNum {
log.Println("readRecord: recordNum >= opRecord.RecordNum")
return opRecord, nil
}
}
}
}
}
default:
return invalidOpRecord, errors.New(funcName + "encountered an invalid intermediate block")
}
block = prevBlock.(Block)
}
return invalidOpRecord, rfslib.FileDoesNotExistError(fmt.Sprintf("miner with id %s could not find file %s\n", m.MinerID, fname))
}
// ListFiles RPC lists all files in the local chain
func (capi *ClientAPI) ListFiles(caller string, fnames *[]string) error {
log.Println("ClientAPI.ListFiles got a call from " + caller)
listedNames, err := capi.miner.listFiles()
if err != nil {
return err
}
*fnames = listedNames
return nil
}
// CountRecords RPC counts the number of records for the given file
func (capi *ClientAPI) CountRecords(fname string, minerRes *rfslib.MinerRes) error {
recordNum, err := capi.miner.countRecords(fname)
if err != nil {
if _, ok := err.(rfslib.FileDoesNotExistError); ok {
*minerRes = rfslib.MinerRes{
HasErr: true,
Error: rfslib.FileDoesNotExist,
}
return nil
}
return err
}
*minerRes = rfslib.MinerRes{
HasErr: false,
Data: recordNum,
}
return nil
}
// getHeight returns the height of the given block in the local chain
func (m *Miner) getHeight(block Block) (int, error) {
if block.hash() == block.prevHash() {
// GenesisBlock case
return 1, nil
}
// OPBlock, NOPBlock case
prevBlock, exists := m.chain.Load(block.prevHash())
if exists {
prevHeight, err := m.getHeight(prevBlock.(Block))
if err == nil {
return prevHeight + 1, nil
}
return prevHeight, err
}
return 1, errors.New("The given NOPBlock/OPBlock starts with an orphaned block:" + block.hash())
}
func (m *Miner) requestPreviousBlocks(blockHash string) error {
_, exists := m.chain.Load(blockHash)
requestedHash := blockHash
for !exists {
found := false
var packet BlockPacket
m.peerMiners.Range(func(remoteMinerID, client interface{}) bool {
// Make a remote asynchronous call
err := client.(*rpc.Client).Call("MinerAPI.GetBlock", requestedHash, &packet)
if err == rpc.ErrShutdown {
log.Println("requestPreviousBlocks: miner", remoteMinerID, "is not up; going to be removed")
m.peerMiners.Delete(remoteMinerID)
return true
} else if err == nil {
found = true
// stop iterating thru peerMiners
return false
}
log.Println("requestPreviousBlocks: ", err, "continue on with other miners")
return true
})
if found {
requestedBlock, err := loadBlock(packet)
if err != nil {
log.Println(err)
return err
}
m.chain.Store(requestedHash, requestedBlock)
fmt.Println("requestPreviousBlocks successed:", requestedBlock.hash())
requestedHash = requestedBlock.prevHash()
_, exists = m.chain.Load(requestedHash)
fmt.Println("requestPreviousBlocks: prevb", exists, requestedHash)
} else {
return errors.New("Cannot find the requested block " + requestedHash + "from other peer miners")
}
}
return nil
}
func (m *Miner) updateChainTip(newBlock Block) error {
prevBlock, exists := m.chain.Load(newBlock.prevHash())
// log.Println("updateChainTip: with hash", newBlock.hash(), newBlock.prevHash())
if exists {
inChainTips := false
currentHeight := 0
m.chainTips.Range(func(blockHash, height interface{}) bool {
// log.Println("chaintip:", blockHash, height)
if blockHash.(string) == prevBlock.(Block).hash() {
inChainTips = true
currentHeight = height.(int)
return false
}
return true
})
if inChainTips {
// we are the first one to work on an original branch
// want to add the new block and remove the old one
m.chainTips.Store(newBlock.hash(), currentHeight+1)
m.chainTips.Delete(newBlock.prevHash())
} else {
// this is a fork of another branch
log.Println("updateChainTip: this block is not in chaintips", newBlock.hash())
prevHeight, err := m.getHeight(prevBlock.(Block))
if err == nil {
m.chainTips.Store(newBlock.hash(), prevHeight+1)
// TODO: be aware of possible side effects
// m.chainTips.Delete(newBlock.prevHash())
} else {
// ask other miners for the previous block?
return err
}
}
return nil
}
return errors.New("updateChainTip: cannot find the previous block")
}
// getBalance finds the current balance along the chain starting
func (m *Miner) getBalance(block Block, minerID string) (uint32, error) {
var mostRecentBalance uint32
var recentTrasactionFee uint32
for block.hash() != block.prevHash() {
switch t := block.(type) {
case NOPBlock:
if t.MinerID == minerID {
mostRecentBalance = t.MinerBalance
return mostRecentBalance - recentTrasactionFee, nil
}
case OPBlock:
if t.MinerID == minerID {
mostRecentBalance = t.MinerBalance
return mostRecentBalance - recentTrasactionFee, nil
}
for _, record := range t.Records {
if record.MinerID == minerID {
if record.OperationType == "append" {
recentTrasactionFee++
} else if record.OperationType == "create" {
recentTrasactionFee += uint32(m.NumCoinsPerFileCreate)
}
}
}
default:
return 0, errors.New("getBalance: encountered an unknown block")
}
prevBlock, exists := m.chain.Load(block.prevHash())
if exists {
block = prevBlock.(Block)
if block.hash() == block.prevHash() {
break
}
} else {
return 0, errors.New("getBalance: this chain does not have a valid head")
}
}
return 0, nil
}
func (m *Miner) addBlock(block Block) error {
err := m.validateBlock(block)