-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathprocessor.go
More file actions
1266 lines (1029 loc) · 34.5 KB
/
processor.go
File metadata and controls
1266 lines (1029 loc) · 34.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 FactomProject Authors. All rights reserved.
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.
// github.com/alexcesaro/log/golog (MIT License)
// Processor is the engine of Factom.
// It processes all of the incoming messages from the network.
// It syncs up with peers and build blocks based on the process lists and a
// timed schedule.
// For details, please refer to:
// https://github.com/FactomProject/FactomDocs/blob/master/FactomLedgerbyConsensus.pdf
package process
import (
"bytes"
"errors"
"fmt"
"sort"
"strconv"
"strings"
"time"
"github.com/FactomProject/FactomCode/anchor"
"github.com/FactomProject/FactomCode/common"
"github.com/FactomProject/FactomCode/consensus"
cp "github.com/FactomProject/FactomCode/controlpanel"
"github.com/FactomProject/FactomCode/database"
"github.com/FactomProject/FactomCode/util"
"github.com/FactomProject/btcd/wire"
fct "github.com/FactomProject/factoid"
"github.com/FactomProject/factoid/block"
"github.com/FactomProject/go-spew/spew"
)
var _ = (*block.FBlock)(nil)
var _ = util.Trace
var (
db database.Db // database
dchain *common.DChain //Directory Block Chain
ecchain *common.ECChain //Entry Credit Chain
achain *common.AdminChain //Admin Chain
fchain *common.FctChain // factoid Chain
fchainID *common.Hash
inMsgQueue chan wire.FtmInternalMsg //incoming message queue for factom application messages
outMsgQueue chan wire.FtmInternalMsg //outgoing message queue for factom application messages
inCtlMsgQueue chan wire.FtmInternalMsg //incoming message queue for factom control messages
outCtlMsgQueue chan wire.FtmInternalMsg //outgoing message queue for factom control messages
//TODO: To be moved to ftmMemPool??
chainIDMap map[string]*common.EChain // ChainIDMap with chainID string([32]byte) as key
commitChainMap = make(map[string]*common.CommitChain, 0)
commitEntryMap = make(map[string]*common.CommitEntry, 0)
eCreditMap map[string]int32 // eCreditMap with public key string([32]byte) as key, credit balance as value
chainIDMapBackup map[string]*common.EChain //previous block bakcup - ChainIDMap with chainID string([32]byte) as key
eCreditMapBackup map[string]int32 // backup from previous block - eCreditMap with public key string([32]byte) as key, credit balance as value
fMemPool *ftmMemPool
plMgr *consensus.ProcessListMgr
lastDirBlockTimestamp uint32
//Server Private key and Public key for milestone 1
serverPrivKey common.PrivateKey
serverPubKey common.PublicKey
FactoshisPerCredit uint64 // .001 / .15 * 100000000 (assuming a Factoid is .15 cents, entry credit = .1 cents
FactomdUser string
FactomdPass string
zeroHash = common.NewHash()
SafeStop bool
SafeStopDone bool
)
var (
directoryBlockInSeconds int
dataStorePath string
ldbpath string
nodeMode string
devNet bool
serverPrivKeyHex string
serverIndex = common.NewServerIndexNumber()
)
// Get the configurations
func LoadConfigurations(cfg *util.FactomdConfig) {
//setting the variables by the valued form the config file
logLevel = cfg.Log.LogLevel
dataStorePath = cfg.App.DataStorePath
ldbpath = cfg.App.LdbPath
directoryBlockInSeconds = cfg.App.DirectoryBlockInSeconds
nodeMode = cfg.App.NodeMode
serverPrivKeyHex = cfg.App.ServerPrivKey
cp.CP.SetPort(cfg.Controlpanel.Port)
FactomdUser = cfg.Btc.RpcUser
FactomdPass = cfg.Btc.RpcPass
}
// Initialize the processor
func initProcessor() {
wire.Init()
// init server private key or pub key
initServerKeys()
// init mem pools
fMemPool = new(ftmMemPool)
fMemPool.init_ftmMemPool()
// init wire.FChainID
wire.FChainID = common.NewHash()
wire.FChainID.SetBytes(common.FACTOID_CHAINID)
FactoshisPerCredit = 666666 // .001 / .15 * 100000000 (assuming a Factoid is .15 cents, entry credit = .1 cents
// init Directory Block Chain
initDChain()
procLog.Info("Loaded ", dchain.NextDBHeight, " Directory blocks for chain: "+dchain.ChainID.String())
// init Entry Credit Chain
initECChain()
procLog.Info("Loaded ", ecchain.NextBlockHeight, " Entry Credit blocks for chain: "+ecchain.ChainID.String())
// init Admin Chain
initAChain()
procLog.Info("Loaded ", achain.NextBlockHeight, " Admin blocks for chain: "+achain.ChainID.String())
initFctChain()
//common.FactoidState.LoadState()
procLog.Info("Loaded ", fchain.NextBlockHeight, " factoid blocks for chain: "+fchain.ChainID.String())
//Init anchor for server
if nodeMode == common.SERVER_NODE {
anchor.InitAnchor(db, inMsgQueue, serverPrivKey)
}
// build the Genesis blocks if the current height is 0
if dchain.NextDBHeight == 0 && nodeMode == common.SERVER_NODE {
buildGenesisBlocks()
} else {
// To be improved in milestone 2
SignDirectoryBlock()
}
// init process list manager
initProcessListMgr()
// init Entry Chains
initEChains()
for _, chain := range chainIDMap {
initEChainFromDB(chain)
procLog.Info("Loaded ", chain.NextBlockHeight, " blocks for chain: "+chain.ChainID.String())
}
// Validate all dir blocks
err := validateDChain(dchain)
if err != nil {
if nodeMode == common.SERVER_NODE {
panic("Error found in validating directory blocks: " + err.Error())
} else {
dchain.IsValidated = false
}
}
}
// Started from factomd
func Start_Processor(
ldb database.Db,
inMsgQ chan wire.FtmInternalMsg,
outMsgQ chan wire.FtmInternalMsg,
inCtlMsgQ chan wire.FtmInternalMsg,
outCtlMsgQ chan wire.FtmInternalMsg) {
db = ldb
inMsgQueue = inMsgQ
outMsgQueue = outMsgQ
inCtlMsgQueue = inCtlMsgQ
outCtlMsgQueue = outCtlMsgQ
initProcessor()
// Initialize timer for the open dblock before processing messages
if nodeMode == common.SERVER_NODE {
timer := &BlockTimer{
nextDBlockHeight: dchain.NextDBHeight,
inCtlMsgQueue: inCtlMsgQueue,
}
go timer.StartBlockTimer()
} else {
// start the go routine to process the blocks and entries downloaded
// from peers
time.Sleep(5 * time.Second)
go validateAndStoreBlocks(fMemPool, db, dchain, outCtlMsgQueue)
}
// Process msg from the incoming queue one by one
for {
queueloop:
for {
select {
case msg, ok := <-inMsgQ:
if ok {
if err := serveMsgRequest(msg); err != nil {
procLog.Error(err)
}
}
case ctlMsg, ok := <-inCtlMsgQueue:
if ok {
if err := serveMsgRequest(ctlMsg); err != nil {
procLog.Error(err)
}
}
default:
time.Sleep(time.Duration(10) * time.Millisecond)
if SafeStop {
procLog.Info("Closing database")
db.Close()
procLog.Info("Database closed")
SafeStopDone = true
}
break queueloop
}
}
}
}
// Serve the "fast lane" incoming control msg from inCtlMsgQueue
func serveCtlMsgRequest(msg wire.FtmInternalMsg) error {
switch msg.Command() {
case wire.CmdCommitChain:
default:
return errors.New("1 Message type unsupported:" + spew.Sdump(msg))
}
return nil
}
// Serve incoming msg from inMsgQueue
func serveMsgRequest(msg wire.FtmInternalMsg) error {
switch msg.Command() {
case wire.CmdCommitChain:
msgCommitChain, ok := msg.(*wire.MsgCommitChain)
if ok && msgCommitChain.IsValid() {
h := msgCommitChain.CommitChain.GetSigHash().Bytes()
t := msgCommitChain.CommitChain.GetMilliTime() / 1000
if !IsTSValid(h, t) {
return fmt.Errorf("Timestamp invalid on Commit Chain")
}
err := processCommitChain(msgCommitChain)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + spew.Sdump(msg))
}
// Broadcast the msg to the network if no errors
outMsgQueue <- msg
case wire.CmdCommitEntry:
msgCommitEntry, ok := msg.(*wire.MsgCommitEntry)
if ok && msgCommitEntry.IsValid() {
h := msgCommitEntry.CommitEntry.GetSigHash().Bytes()
t := msgCommitEntry.CommitEntry.GetMilliTime() / 1000
if !IsTSValid(h, t) {
return fmt.Errorf("Timestamp invalid on Commit Entry")
}
err := processCommitEntry(msgCommitEntry)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + spew.Sdump(msg))
}
// Broadcast the msg to the network if no errors
outMsgQueue <- msg
case wire.CmdRevealEntry:
msgRevealEntry, ok := msg.(*wire.MsgRevealEntry)
if ok && msgRevealEntry.IsValid() {
err := processRevealEntry(msgRevealEntry)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + spew.Sdump(msg))
}
// Broadcast the msg to the network if no errors
outMsgQueue <- msg
case wire.CmdInt_EOM:
if nodeMode == common.SERVER_NODE {
msgEom, ok := msg.(*wire.MsgInt_EOM)
if !ok {
return errors.New("Error in build blocks:" + spew.Sdump(msg))
}
procLog.Infof("PROCESSOR: End of minute msg - wire.CmdInt_EOM:%+v\n", msg)
common.FactoidState.EndOfPeriod(int(msgEom.EOM_Type))
if msgEom.EOM_Type == wire.END_MINUTE_10 {
// Process from Orphan pool before the end of process list
processFromOrphanPool()
// Pass the Entry Credit Exchange Rate into the Factoid component
msgEom.EC_Exchange_Rate = FactoshisPerCredit
plMgr.AddMyProcessListItem(msgEom, nil, wire.END_MINUTE_10)
// Set exchange rate in the Factoid State
common.FactoidState.SetFactoshisPerEC(FactoshisPerCredit)
err := buildBlocks()
if err != nil {
return err
}
} else if wire.END_MINUTE_1 <= msgEom.EOM_Type && msgEom.EOM_Type < wire.END_MINUTE_10 {
ack, err := plMgr.AddMyProcessListItem(msgEom, nil, msgEom.EOM_Type)
if err != nil {
return err
}
if ack.ChainID == nil {
ack.ChainID = dchain.ChainID
}
// Broadcast the ack to the network if no errors
//outMsgQueue <- ack
}
cp.CP.AddUpdate(
"MinMark", // tag
"status", // Category
"Progress", // Title
fmt.Sprintf("End of Minute %v\n", msgEom.EOM_Type)+ // Message
fmt.Sprintf("Directory Block Height %v", dchain.NextDBHeight),
0)
}
case wire.CmdDirBlock:
if nodeMode == common.SERVER_NODE {
break
}
dirBlock, ok := msg.(*wire.MsgDirBlock)
if ok {
err := processDirBlock(dirBlock)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + fmt.Sprintf("%+v", msg))
}
case wire.CmdFBlock:
if nodeMode == common.SERVER_NODE {
break
}
fblock, ok := msg.(*wire.MsgFBlock)
if ok {
err := processFBlock(fblock)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + fmt.Sprintf("%+v", msg))
}
case wire.CmdFactoidTX:
// First check that the message is good, and is valid. If not,
// continue processing commands.
msgFactoidTX, ok := msg.(*wire.MsgFactoidTX)
if !ok || !msgFactoidTX.IsValid() {
break
}
// prevent replay attacks
{
h := msgFactoidTX.Transaction.GetSigHash().Bytes()
t := int64(msgFactoidTX.Transaction.GetMilliTimestamp() / 1000)
if !IsTSValid(h, t) {
return fmt.Errorf("Timestamp invalid on Factoid Transaction")
}
}
// Handle the server case
if nodeMode == common.SERVER_NODE {
t := msgFactoidTX.Transaction
txnum := len(common.FactoidState.GetCurrentBlock().GetTransactions())
if common.FactoidState.AddTransaction(txnum, t) == nil {
if err := processBuyEntryCredit(msgFactoidTX); err != nil {
return err
}
}
} else {
// Handle the client case
outMsgQueue <- msg
}
case wire.CmdABlock:
if nodeMode == common.SERVER_NODE {
break
}
ablock, ok := msg.(*wire.MsgABlock)
if ok {
err := processABlock(ablock)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + fmt.Sprintf("%+v", msg))
}
case wire.CmdECBlock:
if nodeMode == common.SERVER_NODE {
break
}
cblock, ok := msg.(*wire.MsgECBlock)
if ok {
err := procesECBlock(cblock)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + fmt.Sprintf("%+v", msg))
}
case wire.CmdEBlock:
if nodeMode == common.SERVER_NODE {
break
}
eblock, ok := msg.(*wire.MsgEBlock)
if ok {
err := processEBlock(eblock)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + fmt.Sprintf("%+v", msg))
}
case wire.CmdEntry:
if nodeMode == common.SERVER_NODE {
break
}
entry, ok := msg.(*wire.MsgEntry)
if ok {
err := processEntry(entry)
if err != nil {
return err
}
} else {
return errors.New("Error in processing msg:" + fmt.Sprintf("%+v", msg))
}
default:
return errors.New("Message type unsupported:" + fmt.Sprintf("%+v", msg))
}
return nil
}
// processAcknowledgement validates the ack and adds it to processlist
func processAcknowledgement(msg *wire.MsgAcknowledgement) error {
// Error condiftion for Milestone 1
if nodeMode == common.SERVER_NODE {
return errors.New("Server received msg:" + msg.Command())
}
// Validate the signiture
bytes, err := msg.GetBinaryForSignature()
if err != nil {
return err
}
if !serverPubKey.Verify(bytes, &msg.Signature) {
return errors.New(fmt.Sprintf("Invalid signature in Ack = %s\n", spew.Sdump(msg)))
}
// Update the next block height in dchain
if msg.Height > dchain.NextDBHeight {
dchain.NextDBHeight = msg.Height
}
// Update the next block height in db
if int64(msg.Height) > db.FetchNextBlockHeightCache() {
db.UpdateNextBlockHeightCache(msg.Height)
}
return nil
}
// processRevealEntry validates the MsgRevealEntry and adds it to processlist
func processRevealEntry(msg *wire.MsgRevealEntry) error {
e := msg.Entry
bin, _ := e.MarshalBinary()
h, _ := wire.NewShaHash(e.Hash().Bytes())
// Check if the chain id is valid
if e.ChainID.IsSameAs(zeroHash) || e.ChainID.IsSameAs(dchain.ChainID) || e.ChainID.IsSameAs(achain.ChainID) ||
e.ChainID.IsSameAs(ecchain.ChainID) || e.ChainID.IsSameAs(fchain.ChainID) {
return fmt.Errorf("This entry chain is not supported: %s", e.ChainID.String())
}
if c, ok := commitEntryMap[e.Hash().String()]; ok {
if chainIDMap[e.ChainID.String()] == nil {
fMemPool.addOrphanMsg(msg, h)
return fmt.Errorf("This chain is not supported: %s",
msg.Entry.ChainID.String())
}
// Calculate the entry credits required for the entry
cred, err := util.EntryCost(bin)
if err != nil {
return err
}
if c.Credits < cred {
fMemPool.addOrphanMsg(msg, h)
return fmt.Errorf("Credit needs to paid first before an entry is revealed: %s", e.Hash().String())
}
// Add the msg to the Mem pool
fMemPool.addMsg(msg, h)
// Add to MyPL if Server Node
if nodeMode == common.SERVER_NODE {
if plMgr.IsMyPListExceedingLimit() {
procLog.Warning("Exceeding MyProcessList size limit!")
return fMemPool.addOrphanMsg(msg, h)
}
ack, err := plMgr.AddMyProcessListItem(msg, h,
wire.ACK_REVEAL_ENTRY)
if err != nil {
return err
} else {
// Broadcast the ack to the network if no errors
outMsgQueue <- ack
}
}
delete(commitEntryMap, e.Hash().String())
return nil
} else if c, ok := commitChainMap[e.Hash().String()]; ok { //Reveal chain ---------------------------
if chainIDMap[e.ChainID.String()] != nil {
fMemPool.addOrphanMsg(msg, h)
return fmt.Errorf("This chain is not supported: %s",
msg.Entry.ChainID.String())
}
// add new chain to chainIDMap
newChain := common.NewEChain()
newChain.ChainID = e.ChainID
newChain.FirstEntry = e
chainIDMap[e.ChainID.String()] = newChain
// Calculate the entry credits required for the entry
cred, err := util.EntryCost(bin)
if err != nil {
return err
}
// 10 credit is additional for the chain creation
if c.Credits < cred+10 {
fMemPool.addOrphanMsg(msg, h)
return fmt.Errorf("Credit needs to paid first before an entry is revealed: %s", e.Hash().String())
}
//validate chain id for the first entry
expectedChainID := common.NewChainID(e)
if !expectedChainID.IsSameAs(e.ChainID) {
return fmt.Errorf("Invalid ChainID for entry: %s", e.Hash().String())
}
//validate chainid hash in the commitChain
chainIDHash := common.DoubleSha(e.ChainID.Bytes())
if !bytes.Equal(c.ChainIDHash.Bytes()[:], chainIDHash[:]) {
return fmt.Errorf("RevealChain's chainid hash does not match with CommitChain: %s", e.Hash().String())
}
//validate Weld in the commitChain
weld := common.DoubleSha(append(c.EntryHash.Bytes(), e.ChainID.Bytes()...))
if !bytes.Equal(c.Weld.Bytes()[:], weld[:]) {
return fmt.Errorf("RevealChain's weld does not match with CommitChain: %s", e.Hash().String())
}
// Add the msg to the Mem pool
fMemPool.addMsg(msg, h)
// Add to MyPL if Server Node
if nodeMode == common.SERVER_NODE {
if plMgr.IsMyPListExceedingLimit() {
procLog.Warning("Exceeding MyProcessList size limit!")
return fMemPool.addOrphanMsg(msg, h)
}
ack, err := plMgr.AddMyProcessListItem(msg, h,
wire.ACK_REVEAL_CHAIN)
if err != nil {
return err
} else {
// Broadcast the ack to the network if no errors
outMsgQueue <- ack
}
}
delete(commitChainMap, e.Hash().String())
return nil
} else {
return fmt.Errorf("No commit for entry")
}
return nil
}
// processCommitEntry validates the MsgCommitEntry and adds it to processlist
func processCommitEntry(msg *wire.MsgCommitEntry) error {
c := msg.CommitEntry
// check that the CommitChain is fresh
if !c.InTime() {
return fmt.Errorf("Cannot commit chain, CommitChain must be timestamped within 24 hours of commit")
}
// check to see if the EntryHash has already been committed
if _, exist := commitEntryMap[c.EntryHash.String()]; exist {
return fmt.Errorf("Cannot commit entry, entry has already been commited")
}
if c.Credits > common.MAX_ENTRY_CREDITS {
return fmt.Errorf("Commit entry exceeds the max entry credit limit:" + c.EntryHash.String())
}
// Check the entry credit balance
if eCreditMap[string(c.ECPubKey[:])] < int32(c.Credits) {
return fmt.Errorf("Not enough credits for CommitEntry")
}
// add to the commitEntryMap
commitEntryMap[c.EntryHash.String()] = c
// Server: add to MyPL
if nodeMode == common.SERVER_NODE {
// deduct the entry credits from the eCreditMap
eCreditMap[string(c.ECPubKey[:])] -= int32(c.Credits)
h, _ := msg.Sha()
if plMgr.IsMyPListExceedingLimit() {
procLog.Warning("Exceeding MyProcessList size limit!")
return fMemPool.addOrphanMsg(msg, &h)
}
ack, err := plMgr.AddMyProcessListItem(msg, &h, wire.ACK_COMMIT_ENTRY)
if err != nil {
return err
} else {
// Broadcast the ack to the network if no errors
outMsgQueue <- ack
}
}
return nil
}
// processCommitChain validates the MsgCommitChain and adds it to processlist
func processCommitChain(msg *wire.MsgCommitChain) error {
c := msg.CommitChain
// check that the CommitChain is fresh
if !c.InTime() {
return fmt.Errorf("Cannot commit chain, CommitChain must be timestamped within 24 hours of commit")
}
// check to see if the EntryHash has already been committed
if _, exist := commitChainMap[c.EntryHash.String()]; exist {
return fmt.Errorf("Cannot commit chain, first entry for chain already exists")
}
if c.Credits > common.MAX_CHAIN_CREDITS {
return fmt.Errorf("Commit chain exceeds the max entry credit limit:" + c.EntryHash.String())
}
// Check the entry credit balance
if eCreditMap[string(c.ECPubKey[:])] < int32(c.Credits) {
return fmt.Errorf("Not enough credits for CommitChain")
}
// add to the commitChainMap
commitChainMap[c.EntryHash.String()] = c
// Server: add to MyPL
if nodeMode == common.SERVER_NODE {
// deduct the entry credits from the eCreditMap
eCreditMap[string(c.ECPubKey[:])] -= int32(c.Credits)
h, _ := msg.Sha()
if plMgr.IsMyPListExceedingLimit() {
procLog.Warning("Exceeding MyProcessList size limit!")
return fMemPool.addOrphanMsg(msg, &h)
}
ack, err := plMgr.AddMyProcessListItem(msg, &h, wire.ACK_COMMIT_CHAIN)
if err != nil {
return err
} else {
// Broadcast the ack to the network if no errors
outMsgQueue <- ack
}
}
return nil
}
// processBuyEntryCredit validates the MsgCommitChain and adds it to processlist
func processBuyEntryCredit(msg *wire.MsgFactoidTX) error {
// Update the credit balance in memory
for _, v := range msg.Transaction.GetECOutputs() {
pub := new([32]byte)
copy(pub[:], v.GetAddress().Bytes())
cred := int32(v.GetAmount() / uint64(FactoshisPerCredit))
eCreditMap[string(pub[:])] += cred
}
h, _ := msg.Sha()
if plMgr.IsMyPListExceedingLimit() {
procLog.Warning("Exceeding MyProcessList size limit!")
return fMemPool.addOrphanMsg(msg, &h)
}
if _, err := plMgr.AddMyProcessListItem(msg, &h, wire.ACK_FACTOID_TX); err != nil {
return err
}
return nil
}
// Process Orphan pool before the end of 10 min
func processFromOrphanPool() error {
for k, msg := range fMemPool.orphans {
switch msg.Command() {
case wire.CmdCommitChain:
msgCommitChain, _ := msg.(*wire.MsgCommitChain)
err := processCommitChain(msgCommitChain)
if err != nil {
procLog.Info("Error in processing orphan msgCommitChain:" + err.Error())
continue
}
delete(fMemPool.orphans, k)
case wire.CmdCommitEntry:
msgCommitEntry, _ := msg.(*wire.MsgCommitEntry)
err := processCommitEntry(msgCommitEntry)
if err != nil {
procLog.Info("Error in processing orphan msgCommitEntry:" + err.Error())
continue
}
delete(fMemPool.orphans, k)
case wire.CmdRevealEntry:
msgRevealEntry, _ := msg.(*wire.MsgRevealEntry)
err := processRevealEntry(msgRevealEntry)
if err != nil {
procLog.Info("Error in processing orphan msgRevealEntry:" + err.Error())
continue
}
delete(fMemPool.orphans, k)
}
}
return nil
}
func buildRevealEntry(msg *wire.MsgRevealEntry) {
chain := chainIDMap[msg.Entry.ChainID.String()]
// store the new entry in db
db.InsertEntry(msg.Entry)
err := chain.NextBlock.AddEBEntry(msg.Entry)
if err != nil {
panic("Error while adding Entity to Block:" + err.Error())
}
}
func buildIncreaseBalance(msg *wire.MsgFactoidTX) {
t := msg.Transaction
for i, ecout := range t.GetECOutputs() {
ib := common.NewIncreaseBalance()
pub := new([32]byte)
copy(pub[:], ecout.GetAddress().Bytes())
ib.ECPubKey = pub
th := common.NewHash()
th.SetBytes(t.GetHash().Bytes())
ib.TXID = th
cred := int32(ecout.GetAmount() / uint64(FactoshisPerCredit))
ib.NumEC = uint64(cred)
ib.Index = uint64(i)
ecchain.NextBlock.AddEntry(ib)
}
}
func buildCommitEntry(msg *wire.MsgCommitEntry) {
ecchain.NextBlock.AddEntry(msg.CommitEntry)
}
func buildCommitChain(msg *wire.MsgCommitChain) {
ecchain.NextBlock.AddEntry(msg.CommitChain)
}
func buildRevealChain(msg *wire.MsgRevealEntry) {
chain := chainIDMap[msg.Entry.ChainID.String()]
// Store the new chain in db
db.InsertChain(chain)
// Chain initialization
initEChainFromDB(chain)
// store the new entry in db
db.InsertEntry(chain.FirstEntry)
err := chain.NextBlock.AddEBEntry(chain.FirstEntry)
if err != nil {
panic(fmt.Sprintf(`Error while adding the First Entry to Block: %s`,
err.Error()))
}
}
// Loop through the Process List items and get the touched chains
// Put End-Of-Minute marker in the entry chains
func buildEndOfMinute(pl *consensus.ProcessList, pli *consensus.ProcessListItem) {
tmpChains := make(map[string]*common.EChain)
for _, v := range pl.GetPLItems()[:pli.Ack.Index] {
if v.Ack.Type == wire.ACK_REVEAL_ENTRY ||
v.Ack.Type == wire.ACK_REVEAL_CHAIN {
cid := v.Msg.(*wire.MsgRevealEntry).Entry.ChainID.String()
tmpChains[cid] = chainIDMap[cid]
} else if wire.END_MINUTE_1 <= v.Ack.Type &&
v.Ack.Type <= wire.END_MINUTE_10 {
tmpChains = make(map[string]*common.EChain)
}
}
for _, v := range tmpChains {
v.NextBlock.AddEndOfMinuteMarker(pli.Ack.Type)
}
// Add it to the entry credit chain
cbEntry := common.NewMinuteNumber()
cbEntry.Number = pli.Ack.Type
ecchain.NextBlock.AddEntry(cbEntry)
// Add it to the admin chain
abEntries := achain.NextBlock.ABEntries
if len(abEntries) > 0 && abEntries[len(abEntries)-1].Type() != common.TYPE_MINUTE_NUM {
achain.NextBlock.AddEndOfMinuteMarker(pli.Ack.Type)
}
}
// build Genesis blocks
func buildGenesisBlocks() error {
//Set the timestamp for the genesis block
t, err := time.Parse(time.RFC3339, common.GENESIS_BLK_TIMESTAMP)
if err != nil {
panic("Not able to parse the genesis block time stamp")
}
dchain.NextBlock.Header.Timestamp = uint32(t.Unix() / 60)
// Allocate the first two dbentries for ECBlock and Factoid block
dchain.AddDBEntry(&common.DBEntry{}) // AdminBlock
dchain.AddDBEntry(&common.DBEntry{}) // ECBlock
dchain.AddDBEntry(&common.DBEntry{}) // Factoid block
// Entry Credit Chain
cBlock := newEntryCreditBlock(ecchain)
procLog.Debugf("buildGenesisBlocks: cBlock=%s\n", spew.Sdump(cBlock))
dchain.AddECBlockToDBEntry(cBlock)
exportECChain(ecchain)
// Admin chain
aBlock := newAdminBlock(achain)
procLog.Debugf("buildGenesisBlocks: aBlock=%s\n", spew.Sdump(aBlock))
dchain.AddABlockToDBEntry(aBlock)
exportAChain(achain)
// factoid Genesis Address
//fchain.NextBlock = block.GetGenesisFBlock(0, FactoshisPerCredit, 10, 200000000000)
fchain.NextBlock = block.GetGenesisFBlock()
FBlock := newFactoidBlock(fchain)
dchain.AddFBlockToDBEntry(FBlock)
exportFctChain(fchain)
// Directory Block chain
procLog.Debug("in buildGenesisBlocks")
dbBlock := newDirectoryBlock(dchain)
// Check block hash if genesis block
if dbBlock.DBHash.String() != common.GENESIS_DIR_BLOCK_HASH {
//Panic for Milestone 1
panic("\nGenesis block hash expected: " + common.GENESIS_DIR_BLOCK_HASH +
"\nGenesis block hash found: " + dbBlock.DBHash.String() + "\n")
}
exportDChain(dchain)
// place an anchor into btc
placeAnchor(dbBlock)
return nil
}
// build blocks from all process lists
func buildBlocks() error {
// Allocate the first three dbentries for Admin block, ECBlock and Factoid block
dchain.AddDBEntry(&common.DBEntry{}) // AdminBlock
dchain.AddDBEntry(&common.DBEntry{}) // ECBlock
dchain.AddDBEntry(&common.DBEntry{}) // factoid
if plMgr != nil && plMgr.MyProcessList.IsValid() {
buildFromProcessList(plMgr.MyProcessList)
}
// Entry Credit Chain
ecBlock := newEntryCreditBlock(ecchain)
dchain.AddECBlockToDBEntry(ecBlock)
exportECBlock(ecBlock)
// Admin chain
aBlock := newAdminBlock(achain)
dchain.AddABlockToDBEntry(aBlock)
exportABlock(aBlock)
// Factoid chain
fBlock := newFactoidBlock(fchain)
dchain.AddFBlockToDBEntry(fBlock)
exportFctBlock(fBlock)
// sort the echains by chain id
var keys []string
for k := range chainIDMap {
keys = append(keys, k)
}
sort.Strings(keys)
// Entry Chains
for _, k := range keys {
chain := chainIDMap[k]
eblock := newEntryBlock(chain)
if eblock != nil {
dchain.AddEBlockToDBEntry(eblock)
}
exportEBlock(eblock)
}
// Directory Block chain
procLog.Debug("in buildBlocks")
dbBlock := newDirectoryBlock(dchain)