-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathdatastructures.go
1579 lines (1366 loc) · 39.5 KB
/
datastructures.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"log"
"math/big"
"sort"
"sync"
"time"
"unsafe"
"github.com/kimborgen/go-merkletree"
)
// only data structures that are common in multiple, disjoint files, should belong here
type Node_InitialMessageToCoordinator struct {
Pub *PubKey
Port int
}
type SelfInfo struct {
Priv *PrivKey
CommitteeID [32]byte
IP string
IsHonest bool
Debug bool
}
type NodeAllInfo struct {
Pub *PubKey
CommitteeID [32]byte
IP string
IsHonest bool
}
type PlaceHolder struct {
t uint
}
type ResponseToNodes struct {
Nodes []NodeAllInfo
GensisisBlocks []*FinalBlock
DebugNode [32]byte
ReconfigurationBlock *ReconfigurationBlock
}
type ByteArrayAndTimestamp struct {
B []byte
T time.Time
}
// Representation of a member beloning to the current committee of a node
type CommitteeMember struct {
Pub *PubKey
IP string
}
// Representation of a committee from the point of view of a node
type Committee struct {
ID [32]byte
BigIntID *big.Int
CurrentLeader *PubKey
Members map[[32]byte]*CommitteeMember
}
func (c *Committee) init(ID [32]byte) {
c.ID = ID
c.BigIntID = new(big.Int).SetBytes(ID[:])
c.Members = make(map[[32]byte]*CommitteeMember)
}
func (c *Committee) addMember(m *CommitteeMember) {
c.Members[m.Pub.Bytes] = m
}
func (c *Committee) safeAddMember(m *CommitteeMember) bool {
if _, ok := c.Members[m.Pub.Bytes]; !ok {
return false
}
c.addMember(m)
return true
}
func (c *Committee) getMemberIDsAsSortedList() [][32]byte {
newList := make([][32]byte, len(c.Members))
i := 0
for _, v := range c.Members {
newList[i] = v.Pub.Bytes
i++
}
sort.Slice(newList, func(i, j int) bool {
return toBigInt(newList[i]).Cmp(toBigInt(newList[j])) < 0
})
//fmt.Println("Sorted list: ", newList)
return newList
}
// Recived transactions that have not been included in a block yet
type TxPool struct {
pool map[[32]byte]*Transaction // TxHash -> Transaction
mux sync.Mutex
}
func (t *TxPool) len() uint {
t.mux.Lock()
defer t.mux.Unlock()
return uint(len(t.pool))
}
func (t *TxPool) init() {
t.pool = make(map[[32]byte]*Transaction)
}
func (t *TxPool) _add(tx *Transaction) {
t.pool[tx.id()] = tx
}
func (t *TxPool) add(tx *Transaction) {
t.mux.Lock()
t._add(tx)
t.mux.Unlock()
}
func (t *TxPool) safeAdd(tx *Transaction) bool {
// only add if there is no transaction with same has
t.mux.Lock()
defer t.mux.Unlock()
if _, ok := t.pool[tx.id()]; ok {
errFatal(nil, "tx allready in tx pool")
return false
}
t.pool[tx.id()] = tx
return true
}
func (t *TxPool) get(txHash [32]byte) *Transaction {
t.mux.Lock()
defer t.mux.Unlock()
return t.pool[txHash]
}
func (t *TxPool) getAll() []*Transaction {
t.mux.Lock()
defer t.mux.Unlock()
txes := make([]*Transaction, len(t.pool))
i := 0
for _, tx := range t.pool {
txes[i] = tx
i++
}
return txes
}
func (t *TxPool) getEnoughToFillblock(blockSize uint) []*Transaction {
t.mux.Lock()
defer t.mux.Unlock()
txes := []*Transaction{}
size := uint(0)
for _, tx := range t.pool {
txes = append(txes, tx)
tmp := unsafe.Sizeof(*tx)
size += uint(tmp)
if size >= default_B {
break
}
}
log.Printf("Got %d bytes from txpool", size)
return txes
}
func (t *TxPool) _remove(txHash [32]byte) {
delete(t.pool, txHash)
}
func (t *TxPool) remove(txHash [32]byte) {
t.mux.Lock()
defer t.mux.Unlock()
t._remove(txHash)
}
func (t *TxPool) pop(txHash [32]byte) (*Transaction, bool) {
t.mux.Lock()
defer t.mux.Unlock()
tx, ok := t.pool[txHash]
if ok {
delete(t.pool, txHash)
}
return tx, ok
}
func (t *TxPool) _popAll() []*Transaction {
txes := make([]*Transaction, len(t.pool))
i := 0
for _, tx := range t.pool {
txes[i] = tx
i++
}
t.pool = make(map[[32]byte]*Transaction)
return txes
}
func (t *TxPool) popAll() []*Transaction {
t.mux.Lock()
defer t.mux.Unlock()
return t._popAll()
}
func (t *TxPool) processBlock(transactions []*Transaction) {
t.mux.Lock()
defer t.mux.Unlock()
for _, tx := range transactions {
// Remove originaltx, incomming-cross-tx
t._remove(tx.OrigTxHash)
t._remove(tx.Hash)
}
}
// type CrossTxMap struct {
// InputTxID [32]byte
// Finished bool // indicated wheter or not CrossTxResponseID is filled
// CrossTxResponseID [32]byte // Points to UTXO set because the outputs should be there
// Nonce uint
// }
// Keeps track of all cross-txes for an originaltx. Is not needed anymore, but may be usefull for debug purposes, so should be deleted after a while (with processIncommingCrossTxResponse changes).
type CrossTxPool struct {
// set map[[32]byte]map[[32]byte]CrossTxMap // OrigTxID -> InputTxID (in other committe) -> CrossTxMap
original map[[32]byte]*Transaction // hold the original transaction untill final transaction is complete
mux sync.Mutex
}
func (ctp *CrossTxPool) init() {
// ctp.set = make(map[[32]byte]map[[32]byte]CrossTxMap)
ctp.original = make(map[[32]byte]*Transaction)
}
// func (ctp *CrossTxPool) add(origTxID [32]byte, inputTxID [32]byte) {
// ctp.mux.Lock()
// defer ctp.mux.Unlock()
// if _, ok := ctp.set[origTxID]; !ok {
// ctp.set[origTxID] = make(map[[32]byte]CrossTxMap)
// }
// ctp.set[origTxID][inputTxID] = CrossTxMap{InputTxID: inputTxID}
// }
// adds a transaction to pool
func (ctp *CrossTxPool) addOriginalTx(nodeCtx *NodeCtx, tx *Transaction) {
// assuming transaction.whatAmI == originaltx
ctp.mux.Lock()
defer ctp.mux.Unlock()
// ctp.set[tx.OrigTxHash] = make(map[[32]byte]CrossTxMap)
if tx.Hash != [32]byte{} || tx.OrigTxHash == [32]byte{} {
errFatal(nil, "origtx wrong hashes")
}
// for _, inp := range tx.Inputs {
// if txFindClosestCommittee(nodeCtx, inp.TxHash) == nodeCtx.self.CommitteeID {
// ctp.set[tx.OrigTxHash][inp.TxHash] = CrossTxMap{InputTxID: inp.TxHash, Finished: true, CrossTxResponseID: inp.TxHash, Nonce: inp.N}
// } else {
// ctp.set[tx.OrigTxHash][inp.TxHash] = CrossTxMap{InputTxID: inp.TxHash, Finished: false}
// }
// }
ctp.original[tx.OrigTxHash] = tx
}
// func (ctp *CrossTxPool) addResponses(crossTxResponse *Transaction) {
// ctp.mux.Lock()
// defer ctp.mux.Unlock()
// origTxID := crossTxResponse.OrigTxHash
// if _, ok := ctp.set[origTxID]; !ok {
// ctp.set[origTxID] = make(map[[32]byte]CrossTxMap)
// }
// for _, inp := range crossTxResponse.Inputs {
// ctp.set[origTxID][inp.TxHash] = CrossTxMap{InputTxID: inp.TxHash, Finished: true, CrossTxResponseID: crossTxResponse.Hash, Nonce: inp.N}
// }
// }
// func (ctp *CrossTxPool) getMap(origTxID [32]byte) map[[32]byte]CrossTxMap {
// ctp.mux.Lock()
// defer ctp.mux.Unlock()
// if _, ok := ctp.set[origTxID]; !ok {
// errFatal(nil, "No origTxID getMap")
// }
// return ctp.set[origTxID]
// }
// func (ctp *CrossTxPool) getCrossTxMap(origTxID [32]byte, inputTxID [32]byte) *CrossTxMap {
// ctp.mux.Lock()
// defer ctp.mux.Unlock()
// if m, ok := ctp.set[origTxID]; ok {
// if v, ok2 := m[inputTxID]; ok2 {
// if v.Finished {
// mp := new(CrossTxMap)
// mp.CrossTxResponseID = v.CrossTxResponseID
// mp.Finished = v.Finished
// mp.InputTxID = v.InputTxID
// mp.Nonce = v.Nonce
// return mp
// } else {
// return nil
// }
// }
// }
// errFatal(nil, "getCrossTxResponseID orig or input IDs not valid")
// return nil // never reached, but compiler is angry
// }
func (ctp *CrossTxPool) getOriginal(origTxID [32]byte) *Transaction {
ctp.mux.Lock()
defer ctp.mux.Unlock()
if t, ok := ctp.original[origTxID]; ok {
return t
}
return nil
}
func (ctp *CrossTxPool) removeOriginal(origTxID [32]byte) {
ctp.mux.Lock()
defer ctp.mux.Unlock()
delete(ctp.original, origTxID)
}
// func (ctp *CrossTxPool) removeMap(origTxID [32]byte) {
// ctp.mux.Lock()
// defer ctp.mux.Unlock()
// delete(ctp.set, origTxID)
// }
type UTXOSet struct {
set map[[32]byte]map[uint]*OutTx // TxID -> Nonce -> OutTx
mux sync.Mutex
}
func (s *UTXOSet) String() string {
var str string = "[UTXOSet] \n"
for txID, t := range s.set {
str += fmt.Sprintf("\t TxID: %s, Len of set: %d\n", bytes32ToString(txID), len(t))
for n, out := range t {
str += fmt.Sprintf("\tN: %d, out %s\n", n, out)
}
}
return str
}
func (s *UTXOSet) init() {
s.set = make(map[[32]byte]map[uint]*OutTx)
}
func (s *UTXOSet) _add(k [32]byte, oTx *OutTx) {
if len(s.set[k]) == 0 {
s.set[k] = make(map[uint]*OutTx)
}
s.set[k][oTx.N] = oTx
}
func (s *UTXOSet) add(k [32]byte, oTx *OutTx) {
s.mux.Lock()
s._add(k, oTx)
s.mux.Unlock()
}
func (s *UTXOSet) _removeOutput(k [32]byte, N uint) {
delete(s.set[k], N)
if len(s.set[k]) == 0 {
delete(s.set, k)
}
}
func (s *UTXOSet) removeOutput(k [32]byte, N uint) {
s.mux.Lock()
s._removeOutput(k, N)
s.mux.Unlock()
}
func (s *UTXOSet) _get(k [32]byte, N uint) *OutTx {
if len(s.set[k]) == 0 {
// fmt.Println("no key")
return nil
}
v, ok := s.set[k][N]
if !ok {
// fmt.Println("no out")
return nil
}
if N != v.N {
// fmt.Println("Pubkey ", bytesToString(v.PubKey.Bytes[:]))
errFatal(nil, fmt.Sprintf("map nonce %d not equal to tx nonce %d", N, v.N))
}
return v
}
func (s *UTXOSet) get(k [32]byte, N uint) *OutTx {
s.mux.Lock()
defer s.mux.Unlock()
return s._get(k, N)
}
func (s *UTXOSet) verifyNonces() {
s.mux.Lock()
defer s.mux.Unlock()
// fmt.Printf("Total len of UTXO set %d\n", len(s.set))
for _, t := range s.set {
// fmt.Printf("Number of output in tx: %d", len(t))
for k, o := range t {
if k != o.N {
fmt.Printf("\nTxID: %s map nonce N %d and outtx N %d\n", bytesToString(o.PubKey.Bytes[:]), k, o.N)
errFatal(nil, "nonces verifyNonces()")
}
}
}
}
func (s *UTXOSet) _getAndRemove(k [32]byte, N uint) *OutTx {
ret := s._get(k, N)
s._removeOutput(k, N)
return ret
}
func (s *UTXOSet) getAndRemove(k [32]byte, N uint) *OutTx {
s.mux.Lock()
defer s.mux.Unlock()
return s._getAndRemove(k, N)
}
func (s *UTXOSet) getTxOutputsAsList(k [32]byte) *[]*OutTx {
s.mux.Lock()
defer s.mux.Unlock()
if len(s.set[k]) == 0 {
return nil
}
a := make([]*OutTx, len(s.set[k]))
i := 0
for _, v := range s.set[k] {
a[i] = v
}
return &a
}
func (s *UTXOSet) getLenOfEntireSet() int {
s.mux.Lock()
defer s.mux.Unlock()
l := 0
for k := range s.set {
l += len(s.set[k])
}
return l
}
func (s *UTXOSet) _totalValue() uint {
// finds the total value that is in the UTXO set, usefull for each user to know their balance
var tot uint = 0
for _, txid := range s.set {
for _, nonce := range txid {
tot += nonce.Value
}
}
return tot
}
func (s *UTXOSet) totalValue() uint {
// finds the total value that is in the UTXO set, usefull for each user to know their balance
s.mux.Lock()
defer s.mux.Unlock()
var tot uint = 0
for _, txid := range s.set {
for _, nonce := range txid {
tot += nonce.Value
}
}
return tot
}
// only to be used if you own all UTXO's
func (s *UTXOSet) getOutputsToFillValue(value uint) ([]*txIDNonceTuple, bool) {
s.mux.Lock()
defer s.mux.Unlock()
res := []*txIDNonceTuple{}
var remV int = int(value)
for txID := range s.set {
for nonce := range s.set[txID] {
v := s.set[txID][nonce].Value
remV -= int(v)
tnp := new(txIDNonceTuple)
tnp.txID = txID
tnp.n = nonce
if nonce != s.set[txID][nonce].N {
errFatal(nil, fmt.Sprintf("nonces not equal %d %d", nonce, s.set[txID][nonce].N))
}
if remV > 0 {
// take entire output
res = append(res, tnp)
} else {
// take only the required amount
res = append(res, tnp)
return res, true
}
}
}
// did not find enough outputs to fill value
return res, false
}
type txIDNonceTuple struct {
txID [32]byte
n uint
}
type InTx struct {
TxHash [32]byte // output in transaction
N uint // nonce in output in transaction
Sig *Sig // Sig of TxHash, OrigTxHash, N, TxHash, OrigTxHash
}
func (iTx *InTx) String() string {
return fmt.Sprintf("[InTx] TxHash: %s, N: %d, Sig: %s", bytes32ToString(iTx.TxHash), iTx.N, bytesToString(iTx.Sig.bytes()))
}
type OutTx struct {
Value uint // value of UTXO
N uint // nonce/i in output list of tx
PubKey *PubKey
}
func (o *OutTx) String() string {
return fmt.Sprintf("[OutTx] Value: %d, N: %d, PubKey: %s", o.Value, o.N, bytes32ToString(o.PubKey.Bytes))
}
func (o *OutTx) bytes() []byte {
b1 := make([]byte, 8) //uint64 is 8 bytes
binary.LittleEndian.PutUint64(b1, uint64(o.Value))
b2 := make([]byte, 8)
binary.LittleEndian.PutUint64(b2, uint64(o.N))
b3 := o.PubKey.Bytes
return byteSliceAppend(b1, b2, b3[:])
}
func (iTx *InTx) bytesWithSig() []byte {
return byteSliceAppend(iTx.bytesExceptSig(), iTx.Sig.bytes())
}
func (iTx *InTx) bytesExceptSig() []byte {
return byteSliceAppend(iTx.TxHash[:], uintToByte(iTx.N))
}
func (iTx *InTx) getHash(extra [32]byte) [32]byte {
return hash(byteSliceAppend(iTx.bytesExceptSig(), extra[:]))
}
func (iTx *InTx) sign(extra [32]byte, priv *PrivKey) {
iTx.Sig = priv.sign(iTx.getHash(extra))
}
type ProofOfConsensus struct {
GossipHash [32]byte
IntermediateHash [32]byte
MerkleRoot [32]byte
MerkleProof *merkletree.Proof
Signatures []*ConsensusMsg
}
func (poc *ProofOfConsensus) String() string {
str := fmt.Sprintf("[PoC] GossipHash: %s, IntermediateHash: %s\n\tMerkleRoot: %s, MerkleProof: %s,\n\tLen of signatures: %d", bytes32ToString(poc.GossipHash), bytes32ToString(poc.IntermediateHash), bytes32ToString(poc.MerkleRoot), " merkleproofindex: ", poc.MerkleProof.Index)
return str
}
type Transaction struct {
Hash [32]byte // hash of inputs and outputs
OrigTxHash [32]byte // see cross-tx
Inputs []*InTx
Outputs []*OutTx
ProofOfConsensus *ProofOfConsensus
}
func (t *Transaction) String() string {
start := fmt.Sprintf("[TX] Hash: %s, OrigTxHash: %s\n", bytes32ToString(t.Hash), bytes32ToString(t.OrigTxHash))
for _, inp := range t.Inputs {
start += fmt.Sprintln("\n\t", inp)
}
for _, out := range t.Outputs {
start += fmt.Sprintln("\n\t", out)
}
if t.ProofOfConsensus != nil {
start += fmt.Sprintf("\n\t%s\n", t.ProofOfConsensus)
}
return start
}
func (t *Transaction) whatAmI(nodeCtx *NodeCtx) string {
if t.Hash != [32]byte{} && t.OrigTxHash == [32]byte{} {
return "normal"
} else if t.Hash == [32]byte{} && t.OrigTxHash != [32]byte{} && t.Outputs == nil {
return "crosstx"
} else if t.Hash == [32]byte{} && t.OrigTxHash != [32]byte{} && t.Outputs != nil {
return "originaltx"
} else if t.Hash != [32]byte{} && t.OrigTxHash != [32]byte{} && txFindClosestCommittee(nodeCtx, t.OrigTxHash) != nodeCtx.self.CommitteeID {
return "crosstxresponse_C_in"
} else if t.Hash != [32]byte{} && t.OrigTxHash != [32]byte{} && t.ProofOfConsensus != nil {
return "crosstxresponse_C_out"
} else if t.Hash != [32]byte{} && t.OrigTxHash != [32]byte{} && txFindClosestCommittee(nodeCtx, t.OrigTxHash) == nodeCtx.self.CommitteeID {
return "finaltransaction"
} else {
errFatal(nil, "unknown transaction type?")
return "this will never return but compiler is angry"
}
}
func (t *Transaction) calculateHash() [32]byte {
b := []byte{}
for i := range t.Inputs {
b = append(b, t.Inputs[i].bytesExceptSig()...)
}
for i := range t.Outputs {
b = append(b, t.Outputs[i].bytes()...)
}
return hash(byteSliceAppend(b, t.OrigTxHash[:]))
}
// since Hash or OrigTxHash can be nil, we need an identifier for internal functions that will
// work regardless.
func (t *Transaction) id() [32]byte {
id := [32]byte{}
if t.Hash != [32]byte{} {
id = t.Hash
} else {
id = t.OrigTxHash
}
return id
}
func (t *Transaction) ifOrigRetOrigIfNotRetHash() [32]byte {
id := [32]byte{}
if t.OrigTxHash != [32]byte{} {
id = t.OrigTxHash
} else {
id = t.Hash
}
return id
}
func (t *Transaction) setHash() {
t.Hash = t.calculateHash()
}
// Signs all inputs
func (t *Transaction) signInputs(priv *PrivKey) {
for i := range t.Inputs {
// sign InTx.TxID and t.Hash
t.Inputs[i].sign(t.id(), priv)
}
}
func (t *Transaction) encode() []byte {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(t)
ifErrFatal(err, "transaction encode")
return buf.Bytes()
}
func (t *Transaction) decode(b []byte) {
buf := bytes.NewBuffer(b)
dec := gob.NewDecoder(buf)
err := dec.Decode(t)
ifErrFatal(err, "transaction decode")
}
type ProposedBlock struct {
GossipHash [32]byte
// since signatures are not added to block we should use the last seen valdid gossipHash
// Because of synchronity all nodes should have the same signature set, and therefor the
// hash of the final block should be equal among all nodes. But since synchronity is not
// practical, we use the previous gossip hash in this implementation. (the paper does not mention
// such implementation details)
PreviousGossipHash [32]byte
Iteration uint
CommitteeID [32]byte
LeaderPub *PubKey
MerkleRoot [32]byte // Merkle tree of transactions
LeaderSig *Sig // sig of gossiphash
Transactions []*Transaction // not hashed because it is implicitly in MerkleRoot
}
func (b *ProposedBlock) String() string {
str := fmt.Sprintf("\n[ProposedBlock] GossipHash: %s, PreviousGossipHash: %s, Iteration %d, ", bytes32ToString(b.GossipHash), bytes32ToString(b.PreviousGossipHash), b.Iteration)
str += fmt.Sprintf("\n\tCommitteeID: %s, LeaderPub: %s, \n\tmerkleroot: %s, LeaderSig: %s\n", bytes32ToString(b.CommitteeID), bytes32ToString(b.LeaderPub.Bytes), bytes32ToString(b.MerkleRoot), bytesToString(b.LeaderSig.bytes()))
for _, t := range b.Transactions {
str += fmt.Sprintf("\t%s\n", t)
}
return str
}
func (b *ProposedBlock) calculateHash() [32]byte {
hashExcMR := b.calculateHashExceptMerkleRoot()
hashMr := b.calculateHashOfMerkleRoot()
return hash(byteSliceAppend(hashExcMR[:], hashMr[:]))
}
func (b *ProposedBlock) calculateHashExceptMerkleRoot() [32]byte {
pgb := b.PreviousGossipHash[:]
i := uintToByte(b.Iteration)
c := b.CommitteeID[:]
lp := getBytes(b.LeaderPub)
return hash(byteSliceAppend(pgb, i, c, lp))
}
func (b *ProposedBlock) calculateHashOfMerkleRoot() [32]byte {
return hash(b.MerkleRoot[:])
}
func (b *ProposedBlock) isHashesCorrect() bool {
rest := b.calculateHashExceptMerkleRoot()
mr := b.calculateHashOfMerkleRoot()
together := hash(byteSliceAppend(rest[:], mr[:]))
h := b.calculateHash()
// fmt.Println(together, "\n", h, "\n")
// fmt.Println(bytesToString(together[:]), "\n", bytesToString(h[:]))
if bytesToString(together[:]) == bytesToString(h[:]) {
return true
}
return false
}
func (b *ProposedBlock) setHash() {
b.GossipHash = b.calculateHash()
}
func (b *ProposedBlock) encode() []byte {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
err := enc.Encode(b)
ifErrFatal(err, "Proposed block encode")
return buf.Bytes()
}
func (b *ProposedBlock) decode(bArr []byte) {
buf := bytes.NewBuffer(bArr)
dec := gob.NewDecoder(buf)
err := dec.Decode(b)
ifErrFatal(err, "Proposed block decode")
}
// The final block recorded by each member.
// Because of synchronity, the signature set is equal among all nodes
type FinalBlock struct {
ProposedBlock *ProposedBlock
Signatures []*ConsensusMsg
}
// processes the final block by changing the UTXO set and remove transaction from tx pool
func (b *FinalBlock) processBlock(nodeCtx *NodeCtx) {
// assume that signatures and so on are valid because the block has gone trough consensus
// lock utxoSet because we are going to do a lot of changes that must be atomic with the respect to the block
nodeCtx.utxoSet.mux.Lock()
// fmt.Println("Processing block")
// we do not want to proccess new cross-tx'es, or original tx'es (UTXO's in original TX are still spendable)
for _, t := range b.ProposedBlock.Transactions {
what := t.whatAmI(nodeCtx)
// fmt.Println("processBlock: ", what)
// fmt.Println(t)
if what == "normal" {
var tot uint = 0
var totOut uint = 0
// spend inputs
for _, inp := range t.Inputs {
UTXO := nodeCtx.utxoSet._getAndRemove(inp.TxHash, inp.N)
tot += UTXO.Value
}
for _, out := range t.Outputs {
nodeCtx.utxoSet._add(t.Hash, out)
totOut += out.Value
// fmt.Printf("%s Added UTXO with N %d, Value %d and Pub %s\n", bytesToString(nodeCtx.self.CommitteeID[:]), out.N, out.Value, bytesToString(out.PubKey.Bytes[:]))
}
// if signatures is nil, then this is the genesis block
// check if total input == total output, except if this is the gensis block (then signatures will be nil)
if tot != totOut && b.Signatures != nil {
errFatal(nil, fmt.Sprintf("Spent value %d not equal to new unspent value %d", tot, totOut))
}
continue
} else if what == "crosstx" {
// do nothing (no inputs in this committee)
continue
} else if what == "originaltx" {
// add inputs to special map so we can keep track of originalTx and its cross-txes
nodeCtx.crossTxPool.addOriginalTx(nodeCtx, t)
continue
} else if what == "crosstxresponse_C_in" {
// spend inputs, but do not add outputs, because they belong in another committee
for _, inp := range t.Inputs {
nodeCtx.utxoSet._removeOutput(inp.TxHash, inp.N)
}
continue
} else if what == "crosstxresponse_C_out" {
// add outputs, but do not do anything with inputs, because they come from another comittee
if len(t.Inputs) != len(t.Outputs) {
errFatal(nil, "input n output length not equal idkrn")
}
for i := range t.Outputs {
nodeCtx.utxoSet._add(t.Inputs[i].TxHash, t.Outputs[i])
}
// nodeCtx.crossTxPool.addResponses(t)
continue
} else if what == "finaltransaction" {
// get crossTxMap
// all inputs in crossTxMap corresponds to finaltransaction and original transaction
// crossMap := nodeCtx.crossTxPool.getMap(t.OrigTxHash)
original := nodeCtx.crossTxPool.getOriginal(t.OrigTxHash)
if original == nil {
errFatal(nil, fmt.Sprint("original was nil", original))
}
// outputs should be exactly the same in final and original
for _, out := range t.Outputs {
var found bool = false
for _, origOut := range original.Outputs {
if out.Value == origOut.Value && out.N == origOut.N && out.PubKey.Bytes == origOut.PubKey.Bytes {
found = true
break
}
}
if !found {
errFatal(nil, "outputs not equal")
}
}
// var tot uint = 0
var totOut uint = 0
// spend inputs
for _, inp := range t.Inputs {
nodeCtx.utxoSet._getAndRemove(inp.TxHash, inp.N)
// tot += UTXO.Value
}
if t.OrigTxHash != original.OrigTxHash || t.OrigTxHash == [32]byte{} {
errFatal(nil, "orighasshes not equal akjb3")
}
// add outputs
for _, out := range t.Outputs {
nodeCtx.utxoSet._add(t.OrigTxHash, out)
totOut += out.Value
}
// if tot != totOut {
// errFatal(nil, fmt.Sprintf("finaltransaction: Spent value %d not equal to new unspent value %d", tot, totOut))
// }
// remove original tx and crosstxmap from crossTxPool
nodeCtx.crossTxPool.removeOriginal(t.OrigTxHash)
// nodeCtx.crossTxPool.removeMap(t.OrigTxHash)
continue
} else {
errFatal(nil, "unknow whatAmI ")
}
}
// remove transactions from tx pool
nodeCtx.txPool.processBlock(b.ProposedBlock.Transactions)
// print utxo set
// fmt.Println(nodeCtx.utxoSet)
nodeCtx.utxoSet.mux.Unlock()
}
// forces the processing of a block without checking for valid UTXOs. (This is valid only if signature set is valid)
func (b *FinalBlock) forceProcessBlock(nodeCtx *NodeCtx) {
// assume that signatures and so on are valid because the block has gone trough consensus
// lock utxoSet because we are going to do a lot of changes that must be atomic with the respect to the block
nodeCtx.utxoSet.mux.Lock()
// fmt.Println("Processing block")
// we do not want to proccess new cross-tx'es, or original tx'es (UTXO's in original TX are still spendable)
for _, t := range b.ProposedBlock.Transactions {
what := t.whatAmI(nodeCtx)
// fmt.Println("processBlock: ", what)
// fmt.Println(t)
if what == "normal" {
// spend inputs
for _, inp := range t.Inputs {
nodeCtx.utxoSet._removeOutput(inp.TxHash, inp.N)
}
for _, out := range t.Outputs {
nodeCtx.utxoSet._add(t.Hash, out)
// fmt.Printf("%s Added UTXO with N %d, Value %d and Pub %s\n", bytesToString(nodeCtx.self.CommitteeID[:]), out.N, out.Value, bytesToString(out.PubKey.Bytes[:]))
}
// if signatures is nil, then this is the genesis block
// check if total input == total output, except if this is the gensis block (then signatures will be nil)
continue
} else if what == "crosstx" {
// do nothing (no inputs in this committee)
continue
} else if what == "originaltx" {
// add inputs to special map so we can keep track of originalTx and its cross-txes
nodeCtx.crossTxPool.addOriginalTx(nodeCtx, t)
continue
} else if what == "crosstxresponse_C_in" {
// spend inputs, but do not add outputs, because they belong in another committee
for _, inp := range t.Inputs {
nodeCtx.utxoSet._removeOutput(inp.TxHash, inp.N)
}
continue
} else if what == "crosstxresponse_C_out" {
// add outputs, but do not do anything with inputs, because they come from another comittee
if len(t.Inputs) != len(t.Outputs) {
errFatal(nil, "input n output length not equal idkrn")
}
for i := range t.Outputs {
nodeCtx.utxoSet._add(t.Inputs[i].TxHash, t.Outputs[i])
}
// nodeCtx.crossTxPool.addResponses(t)
continue
} else if what == "finaltransaction" {
for _, inp := range t.Inputs {
nodeCtx.utxoSet._removeOutput(inp.TxHash, inp.N)
}
// add outputs
for _, out := range t.Outputs {
nodeCtx.utxoSet._add(t.OrigTxHash, out)
}
// remove original tx and crosstxmap from crossTxPool
nodeCtx.crossTxPool.removeOriginal(t.OrigTxHash)
continue
} else {
errFatal(nil, "unknow whatAmI ")
}
}
// remove transactions from tx pool
nodeCtx.txPool.processBlock(b.ProposedBlock.Transactions)
// print utxo set
// fmt.Println(nodeCtx.utxoSet)
nodeCtx.utxoSet.mux.Unlock()
}
type ConsensusMsg struct {
GossipHash [32]byte
Tag string // propose, echo, accept or pending
Pub *PubKey
Sig *Sig // Sig of the hash of the above
}
func (cMsg *ConsensusMsg) String() string {
return fmt.Sprintf("[cMsg] GossipHash: %s, Tag: %s, Pubkey: %s, Sig: %s\n ", bytes32ToString(cMsg.GossipHash), cMsg.Tag, bytes32ToString(cMsg.Pub.Bytes), bytesToString(cMsg.Sig.bytes()))
}
func (cMsg *ConsensusMsg) calculateHash() [32]byte {
b := byteSliceAppend(cMsg.GossipHash[:], []byte(cMsg.Tag), cMsg.Pub.Bytes[:])
return hash(b)
}
func (cMsg *ConsensusMsg) sign(pk *PrivKey) {
cMsg.Sig = pk.sign(cMsg.calculateHash())
}
type ConsensusMsgs struct {
m map[[32]byte]map[[32]byte]*ConsensusMsg // GossipHash -> Pub.Bytes -> msg
mux sync.Mutex
}
func (cMsgs *ConsensusMsgs) init() {
cMsgs.m = make(map[[32]byte]map[[32]byte]*ConsensusMsg)
}
func (cMsgs *ConsensusMsgs) _initGossipHash(gh [32]byte) {
cMsgs.m[gh] = make(map[[32]byte]*ConsensusMsg)
}
func (cMsgs *ConsensusMsgs) initGossipHash(gh [32]byte) {
cMsgs.mux.Lock()
defer cMsgs.mux.Unlock()
cMsgs._initGossipHash(gh)
}
func (cMsgs *ConsensusMsgs) _exists(gh [32]byte) bool {
_, ok := cMsgs.m[gh]
return ok
}
func (cMsgs *ConsensusMsgs) exists(gh [32]byte) bool {
cMsgs.mux.Lock()
defer cMsgs.mux.Unlock()
return cMsgs._exists(gh)
}
func (cMsgs *ConsensusMsgs) _hasMsgFrom(gh [32]byte, ID [32]byte) bool {
_, ok := cMsgs.m[gh][ID]