forked from mapprotocol/atlas
/
types.go
1195 lines (1023 loc) · 35.7 KB
/
types.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
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package istanbul
import (
"crypto/ecdsa"
"fmt"
"github.com/ethereum/go-ethereum/log"
"io"
"math/big"
"time"
"github.com/Alexfordev/atlas/accounts"
"github.com/Alexfordev/atlas/core/types"
blscrypto "github.com/Alexfordev/atlas/helper/bls"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/rlp"
)
// Decrypt is a decrypt callback function to request an ECIES ciphertext to be
// decrypted
type DecryptFn func(accounts.Account, []byte, []byte, []byte) ([]byte, error)
// SignerFn is a signer callback function to request a header to be signed by a
// backing account.
type SignerFn func(accounts.Account, string, []byte) ([]byte, error)
// BLSSignerFn is a signer callback function to request a message and extra data to be signed by a
// backing account using BLS with a direct or composite hasher,fork,cur *big.Int
type BLSSignerFn func(accounts.Account, []byte, []byte, bool, bool, *big.Int, *big.Int) (blscrypto.SerializedSignature, error)
// HashSignerFn is a signer callback function to request a hash to be signed by a
// backing account.
type HashSignerFn func(accounts.Account, []byte) ([]byte, error)
// Proposal supports retrieving height and serialized block to be used during Istanbul consensus.
type Proposal interface {
// Number retrieves the sequence number of this proposal.
Number() *big.Int
Header() *types.Header
// Hash retrieves the hash of this block
Hash() common.Hash
// ParentHash retrieves the hash of this block's parent
ParentHash() common.Hash
EncodeRLP(w io.Writer) error
DecodeRLP(s *rlp.Stream) error
}
// ## Request ##############################################################
type Request struct {
Proposal Proposal
}
// EncodeRLP serializes b into the Ethereum RLP format.
func (b *Request) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, []interface{}{b.Proposal})
}
// DecodeRLP implements rlp.Decoder, and load the consensus fields from a RLP stream.
func (b *Request) DecodeRLP(s *rlp.Stream) error {
var request struct {
Proposal *types.Block
}
if err := s.Decode(&request); err != nil {
return err
}
b.Proposal = request.Proposal
return nil
}
// ## View ##############################################################
// View includes a round number and a sequence number.
// Sequence is the block number we'd like to commit.
// Each round has a number and is composed by 3 steps: preprepare, prepare and commit.
//
// If the given block is not accepted by validators, a round change will occur
// and the validators start a new round with round+1.
type View struct {
Round *big.Int
Sequence *big.Int
}
func (v *View) String() string {
if v.Round == nil || v.Sequence == nil {
return "Invalid"
}
return fmt.Sprintf("{Round: %d, Sequence: %d}", v.Round.Uint64(), v.Sequence.Uint64())
}
// Cmp compares v and y and returns:
//
// -1 if v < y
// 0 if v == y
// +1 if v > y
func (v *View) Cmp(y *View) int {
if v.Sequence.Cmp(y.Sequence) != 0 {
return v.Sequence.Cmp(y.Sequence)
}
if v.Round.Cmp(y.Round) != 0 {
return v.Round.Cmp(y.Round)
}
return 0
}
// ## RoundChangeCertificate ##############################################################
// To considerably reduce the bandwidth used by the RoundChangeCertificate type (which often
// contains repeated Proposal from different RoundChange messages), we break it apart during
// RLP encoding and then build it back during decoding. Proposals are sent just once, and
// Messages referencing them will use their Hash instead.
type RoundChangeCertificate struct {
RoundChangeMessages []Message
}
func (b *RoundChangeCertificate) IsEmpty() bool {
return len(b.RoundChangeMessages) == 0
}
// EncodeRLP serializes b into the Ethereum RLP format.
func (c *RoundChangeCertificate) EncodeRLP(w io.Writer) error {
proposals, messages, err := c.asValues()
if err != nil {
return err
}
log.Debug("Round change certificate proposals", "count", len(proposals))
return rlp.Encode(w, []interface{}{proposals, messages})
}
// DecodeRLP implements rlp.Decoder, and load the consensus fields from a RLP stream.
func (c *RoundChangeCertificate) DecodeRLP(s *rlp.Stream) error {
var decodestr struct {
Proposals []*types.Block
IndexedMessages []IndexedRoundChangeMessage
}
if err := s.Decode(&decodestr); err != nil {
return err
}
return c.setValues(decodestr.Proposals, decodestr.IndexedMessages)
}
// setValues recreates the RoundChange messages from the props (Proposal set/index) and the
// list of IndexedRoundChangeMessage, which is supposed to be the same as the RoundChange
// Messages but with the proposals just referenced to the Proposals set.
func (c *RoundChangeCertificate) setValues(props []*types.Block, iMess []IndexedRoundChangeMessage) error {
// create a Proposal index from the list
propIndex := make(map[common.Hash]Proposal)
for _, prop := range props {
propIndex[prop.Hash()] = prop
}
// Recreate Messages one by one
mess := make([]Message, len(iMess))
for i, im := range iMess {
mess[i] = Message{
Code: im.Message.Code,
Address: im.Message.Address,
Signature: im.Message.Signature,
}
// Add the proposal to the message if it had one
roundChange, err := im.Message.TryRoundChange()
if err != nil {
return err
}
if proposal, ok := propIndex[im.ProposalHash]; ok {
roundChange.PreparedCertificate.Proposal = proposal
}
setMessageBytes(&mess[i], roundChange)
mess[i].roundChange = roundChange
}
c.RoundChangeMessages = mess
return nil
}
type IndexedRoundChangeMessage struct {
ProposalHash common.Hash
Message Message // PreparedCertificate.Proposal = nil if any
}
// asValues presents the RoundChangeCertificate as values for RLP Serialization.
// This is done using a list of proposals, and the RoundChange messages using
// hash references instead of the full proposal objects, to reduce bandwidth.
func (c *RoundChangeCertificate) asValues() ([]*types.Block, []*IndexedRoundChangeMessage, error) {
var err error
messages := make([]*IndexedRoundChangeMessage, len(c.RoundChangeMessages))
proposalsMap := make(map[common.Hash]*types.Block)
for i, message := range c.RoundChangeMessages {
var proposal *types.Block
proposal, messages[i], err = extractProposal(&message)
if err != nil {
return nil, nil, err
}
if proposal != nil {
// we don't use the height since we know they MUST be the same
proposalsMap[proposal.Hash()] = proposal
}
}
// Iterate values. RLP does not support maps
proposals := make([]*types.Block, len(proposalsMap))
var i = 0
for _, p := range proposalsMap {
proposals[i] = p
i++
}
return proposals, messages, nil
}
func extractProposal(message *Message) (*types.Block, *IndexedRoundChangeMessage, error) {
roundChange, err := message.TryRoundChange()
if err != nil {
return nil, nil, err
}
pc := roundChange.PreparedCertificate
// Assume message.Code = MsgRoundChange
indexedMsg := IndexedRoundChangeMessage{
Message: Message{
Code: message.Code,
Address: message.Address,
Signature: message.Signature,
},
}
if pc.Proposal != nil {
indexedMsg.ProposalHash = pc.Proposal.Hash()
}
curatedPC := EmptyPreparedCertificate()
curatedPC.PrepareOrCommitMessages = pc.PrepareOrCommitMessages
setMessageBytes(&indexedMsg.Message,
&RoundChange{
View: roundChange.View,
PreparedCertificate: curatedPC,
})
return pc.Proposal.(*types.Block), &indexedMsg, nil
}
// ## Preprepare ##############################################################
// NewPreprepareMessage constructs a Message instance with the given sender and
// prePrepare. Both the prePrepare instance and the serialized bytes of
// prePrepare are part of the returned Message.
func NewPreprepareMessage(prePrepare *Preprepare, sender common.Address) *Message {
message := &Message{
Address: sender,
Code: MsgPreprepare,
prePrepare: prePrepare,
}
setMessageBytes(message, prePrepare)
return message
}
type Preprepare struct {
View *View
Proposal Proposal
RoundChangeCertificate RoundChangeCertificate
}
type PreprepareData struct {
View *View
Proposal *types.Block
RoundChangeCertificate RoundChangeCertificate
}
type PreprepareSummary struct {
View *View `json:"view"`
ProposalHash common.Hash `json:"proposalHash"`
RoundChangeCertificateSenders []common.Address `json:"roundChangeCertificateSenders"`
}
func (pp *Preprepare) HasRoundChangeCertificate() bool {
return !pp.RoundChangeCertificate.IsEmpty()
}
func (pp *Preprepare) AsData() *PreprepareData {
return &PreprepareData{
View: pp.View,
Proposal: pp.Proposal.(*types.Block),
RoundChangeCertificate: pp.RoundChangeCertificate,
}
}
func (pp *Preprepare) Summary() *PreprepareSummary {
return &PreprepareSummary{
View: pp.View,
ProposalHash: pp.Proposal.Hash(),
RoundChangeCertificateSenders: MapMessagesToSenders(pp.RoundChangeCertificate.RoundChangeMessages),
}
}
// RLP Encoding ---------------------------------------------------------------
// EncodeRLP serializes b into the Ethereum RLP format.
func (pp *Preprepare) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, pp.AsData())
}
// DecodeRLP implements rlp.Decoder, and load the consensus fields from a RLP stream.
func (pp *Preprepare) DecodeRLP(s *rlp.Stream) error {
var data PreprepareData
if err := s.Decode(&data); err != nil {
return err
}
pp.View, pp.Proposal, pp.RoundChangeCertificate = data.View, data.Proposal, data.RoundChangeCertificate
return nil
}
// ## PreparedCertificate #####################################################
type PreparedCertificate struct {
Proposal Proposal
PrepareOrCommitMessages []Message
}
type PreparedCertificateData struct {
Proposal *types.Block
PrepareOrCommitMessages []Message
}
type PreparedCertificateSummary struct {
ProposalHash common.Hash `json:"proposalHash"`
PrepareSenders []common.Address `json:"prepareSenders"`
CommitSenders []common.Address `json:"commitSenders"`
}
func EmptyPreparedCertificate() PreparedCertificate {
emptyHeader := &types.Header{
Number: big.NewInt(0),
GasUsed: 0,
Time: 0,
}
block := &types.Block{}
block = block.WithRandomness(&types.EmptyRandomness)
block = block.WithEpochSnarkData(&types.EmptyEpochSnarkData)
return PreparedCertificate{
Proposal: block.WithHeader(emptyHeader),
PrepareOrCommitMessages: []Message{},
}
}
func (pc *PreparedCertificate) IsEmpty() bool {
return len(pc.PrepareOrCommitMessages) == 0
}
func (pc *PreparedCertificate) AsData() *PreparedCertificateData {
return &PreparedCertificateData{
Proposal: pc.Proposal.(*types.Block),
PrepareOrCommitMessages: pc.PrepareOrCommitMessages,
}
}
func (pc *PreparedCertificate) Summary() *PreparedCertificateSummary {
var prepareSenders, commitSenders []common.Address
for _, msg := range pc.PrepareOrCommitMessages {
if msg.Code == MsgPrepare {
prepareSenders = append(prepareSenders, msg.Address)
} else {
commitSenders = append(commitSenders, msg.Address)
}
}
return &PreparedCertificateSummary{
ProposalHash: pc.Proposal.Hash(),
PrepareSenders: prepareSenders,
CommitSenders: commitSenders,
}
}
// RLP Encoding ---------------------------------------------------------------
// EncodeRLP serializes b into the Ethereum RLP format.
func (pc *PreparedCertificate) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, pc.AsData())
}
// DecodeRLP implements rlp.Decoder, and load the consensus fields from a RLP stream.
func (pc *PreparedCertificate) DecodeRLP(s *rlp.Stream) error {
var data PreparedCertificateData
if err := s.Decode(&data); err != nil {
return err
}
pc.PrepareOrCommitMessages, pc.Proposal = data.PrepareOrCommitMessages, data.Proposal
return nil
}
// ## RoundChange #############################################################
// NewRoundChangeMessage constructs a Message instance with the given sender and
// roundChange. Both the roundChange instance and the serialized bytes of
// roundChange are part of the returned Message.
func NewRoundChangeMessage(roundChange *RoundChange, sender common.Address) *Message {
message := &Message{
Address: sender,
Code: MsgRoundChange,
roundChange: roundChange,
}
setMessageBytes(message, roundChange)
return message
}
type RoundChange struct {
View *View
PreparedCertificate PreparedCertificate
}
func (b *RoundChange) HasPreparedCertificate() bool {
return !b.PreparedCertificate.IsEmpty()
}
// EncodeRLP serializes b into the Ethereum RLP format.
func (b *RoundChange) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, []interface{}{b.View, &b.PreparedCertificate})
}
// DecodeRLP implements rlp.Decoder, and load the consensus fields from a RLP stream.
func (b *RoundChange) DecodeRLP(s *rlp.Stream) error {
var roundChange struct {
View *View
PreparedCertificate PreparedCertificate
}
if err := s.Decode(&roundChange); err != nil {
return err
}
b.View, b.PreparedCertificate = roundChange.View, roundChange.PreparedCertificate
return nil
}
// ## Subject #################################################################
// NewPrepareMessage constructs a Message instance with the given sender and
// subject. Both the subject instance and the serialized bytes of subject are
// part of the returned Message.
func NewPrepareMessage(subject *Subject, sender common.Address) *Message {
message := &Message{
Address: sender,
Code: MsgPrepare,
prepare: subject,
}
setMessageBytes(message, subject)
return message
}
type Subject struct {
View *View
Digest common.Hash
}
func (s *Subject) String() string {
return fmt.Sprintf("{View: %v, Digest: %v}", s.View, s.Digest.String())
}
// ## CommittedSubject #################################################################
// NewCommitMessage constructs a Message instance with the given sender and
// commit. Both the commit instance and the serialized bytes of commit are
// part of the returned Message.
func NewCommitMessage(commit *CommittedSubject, sender common.Address) *Message {
message := &Message{
Address: sender,
Code: MsgCommit,
committedSubject: commit,
}
setMessageBytes(message, commit)
return message
}
type CommittedSubject struct {
Subject *Subject
CommittedSeal []byte
EpochValidatorSetSeal []byte
}
// ## ForwardMessage #################################################################
// NewForwardMessage constructs a Message instance with the given sender and
// forwardMessage. Both the forwardMessage instance and the serialized bytes of
// fowardMessage are part of the returned Message.
func NewForwardMessage(fowardMessage *ForwardMessage, sender common.Address) *Message {
message := &Message{
Address: sender,
Code: FwdMsg,
forwardMessage: fowardMessage,
}
setMessageBytes(message, fowardMessage)
return message
}
type ForwardMessage struct {
Code uint64
Msg []byte
DestAddresses []common.Address
}
// ===============================================================
//
// define the IstanbulQueryEnode message format, the QueryEnodeMsgCache entries, the queryEnode send function (both the gossip version and the "retrieve from cache" version), and the announce get function
// NewQueryEnodeMessage constructs a Message instance with the given sender and
// queryEnode. Both the queryEnode instance and the serialized bytes of
// queryEnode are part of the returned Message.
func NewQueryEnodeMessage(queryEnode *QueryEnodeData, sender common.Address) *Message {
message := &Message{
Address: sender,
Code: QueryEnodeMsg,
queryEnode: queryEnode,
}
setMessageBytes(message, queryEnode)
return message
}
type EncryptedEnodeURL struct {
DestAddress common.Address
EncryptedEnodeURL []byte
}
func (ee *EncryptedEnodeURL) String() string {
return fmt.Sprintf("{DestAddress: %s, EncryptedEnodeURL length: %d}", ee.DestAddress.String(), len(ee.EncryptedEnodeURL))
}
type QueryEnodeData struct {
EncryptedEnodeURLs []*EncryptedEnodeURL
Version uint
// The timestamp of the node when the message is generated.
// This results in a new hash for a newly generated message so it gets regossiped by other nodes
Timestamp uint
}
func (qed *QueryEnodeData) String() string {
return fmt.Sprintf("{Version: %v, Timestamp: %v, EncryptedEnodeURLs: %v}", qed.Version, qed.Timestamp, qed.EncryptedEnodeURLs)
}
// ==============================================
//
// define the functions that needs to be provided for rlp Encoder/Decoder.
// EncodeRLP serializes ar into the Ethereum RLP format.
func (ee *EncryptedEnodeURL) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, []interface{}{ee.DestAddress, ee.EncryptedEnodeURL})
}
// DecodeRLP implements rlp.Decoder, and load the ar fields from a RLP stream.
func (ee *EncryptedEnodeURL) DecodeRLP(s *rlp.Stream) error {
var msg struct {
DestAddress common.Address
EncryptedEnodeURL []byte
}
if err := s.Decode(&msg); err != nil {
return err
}
ee.DestAddress, ee.EncryptedEnodeURL = msg.DestAddress, msg.EncryptedEnodeURL
return nil
}
// EncodeRLP serializes ad into the Ethereum RLP format.
func (qed *QueryEnodeData) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, []interface{}{qed.EncryptedEnodeURLs, qed.Version, qed.Timestamp})
}
// DecodeRLP implements rlp.Decoder, and load the ad fields from a RLP stream.
func (qed *QueryEnodeData) DecodeRLP(s *rlp.Stream) error {
var msg struct {
EncryptedEnodeURLs []*EncryptedEnodeURL
Version uint
Timestamp uint
}
if err := s.Decode(&msg); err != nil {
return err
}
qed.EncryptedEnodeURLs, qed.Version, qed.Timestamp = msg.EncryptedEnodeURLs, msg.Version, msg.Timestamp
return nil
}
// ## Consensus Message codes ##########################################################
const (
MsgPreprepare uint64 = iota
MsgPrepare
MsgCommit
MsgRoundChange
)
// Message is a wrapper used for all istanbul communication. It encapsulates
// the sender's address, a code that indicates the type of the wrapped message
// and a signature. Message instances also hold a deserialised instance of the
// inner message which can be retrieved by calling the corresponding function
// (Commit(), Preprepare() ... etc).
//
// Messages should be initialised either through the use of one of the
// NewXXXMessage constructors or by calling FromPayload on an empty Message
// instance, these mechanisms ensure that the produced Message instances will
// contain the deserialised inner message instance and the serialised bytes of
// the inner message.
type Message struct {
Code uint64
Msg []byte // The serialised bytes of the innner message.
Address common.Address // The sender address
Signature []byte // Signature of the Message using the private key associated with the "Address" field
// The below fields are the potential inner message instances only one
// should be set for a message instance. These fields are not rlp
// serializable since they are private. They are set when calling
// Message.FromPayload, or at message construction time.
committedSubject *CommittedSubject
prePrepare *Preprepare
prepare *Subject
roundChange *RoundChange
queryEnode *QueryEnodeData
forwardMessage *ForwardMessage
enodeCertificate *EnodeCertificate
versionCertificates []*VersionCertificate
valEnodeShareData *ValEnodesShareData
}
// setMessageBytes sets the Msg field of msg to the rlp serialised bytes of
// innerMessage. If innerMessage fails serialisation then this function
// panics. This is intended for use by NewXXXMessage constructors only.
func setMessageBytes(msg *Message, innerMessage interface{}) {
bytes, err := rlp.EncodeToBytes(innerMessage)
if err != nil {
panic(fmt.Sprintf("attempt to serialise inner message of type %T failed. %s", innerMessage, err))
}
msg.Msg = bytes
}
func (m *Message) Sign(signingFn func(data []byte) ([]byte, error)) error {
// Construct and encode a message with no signature
payloadNoSig, err := m.PayloadNoSig()
if err != nil {
return err
}
m.Signature, err = signingFn(payloadNoSig)
return err
}
func (m *Message) DecodeMessage() error {
var err error
switch m.Code {
case MsgPreprepare:
var p *Preprepare
err = m.decode(&p)
if err != nil {
return err
}
m.prePrepare = p
case MsgPrepare:
var p *Subject
err = m.decode(&p)
m.prepare = p
case MsgCommit:
var cs *CommittedSubject
err = m.decode(&cs)
m.committedSubject = cs
case MsgRoundChange:
var p *RoundChange
err = m.decode(&p)
if err != nil {
return err
}
m.roundChange = p
case QueryEnodeMsg:
var q *QueryEnodeData
err = m.decode(&q)
m.queryEnode = q
case FwdMsg:
var f *ForwardMessage
err = m.decode(&f)
m.forwardMessage = f
case EnodeCertificateMsg:
var e *EnodeCertificate
err = m.decode(&e)
m.enodeCertificate = e
case VersionCertificatesMsg:
var v []*VersionCertificate
err = m.decode(&v)
m.versionCertificates = v
case ValEnodesShareMsg:
var v *ValEnodesShareData
err = m.decode(&v)
m.valEnodeShareData = v
default:
err = fmt.Errorf("unrecognised message code %d", m.Code)
}
return err
}
func (m *Message) DecodeRLP(stream *rlp.Stream) error {
type decodable Message
var d decodable
err := stream.Decode(&d)
if err != nil {
return err
}
*m = Message(d)
if len(m.Msg) == 0 && len(m.Signature) == 0 {
// Empty validator handshake message
return nil
}
return m.DecodeMessage()
}
// FromPayload decodes b into a Message instance it will set one of the private
// fields committedSubject, prePrepare, prepare or roundChange depending on the
// type of the message.
func (m *Message) FromPayload(b []byte, validateFn func([]byte, []byte) (common.Address, error)) error {
// Decode Message
err := rlp.DecodeBytes(b, &m)
if err != nil {
return err
}
// Validate message (on a message without Signature)
if validateFn != nil {
var payload []byte
payload, err = m.PayloadNoSig()
if err != nil {
return err
}
signed_val_addr, err := validateFn(payload, m.Signature)
if err != nil {
return err
}
if signed_val_addr != m.Address {
return ErrInvalidSigner
}
}
return nil
}
func (m *Message) Payload() ([]byte, error) {
return rlp.EncodeToBytes(m)
}
func (m *Message) PayloadNoSig() ([]byte, error) {
return rlp.EncodeToBytes(&Message{
Code: m.Code,
Msg: m.Msg,
Address: m.Address,
Signature: []byte{},
})
}
func (m *Message) decode(val interface{}) error {
return rlp.DecodeBytes(m.Msg, val)
}
func (m *Message) String() string {
return fmt.Sprintf("{Code: %v, Address: %v}", m.Code, m.Address.String())
}
// Commit returns the committed subject if this is a commit message.
func (m *Message) Commit() *CommittedSubject {
return m.committedSubject
}
// Preprepare returns preprepare if this is a preprepare message.
func (m *Message) Preprepare() *Preprepare {
return m.prePrepare
}
// Prepare returns prepare if this is a prepare message.
func (m *Message) Prepare() *Subject {
return m.prepare
}
// Prepare returns round change if this is a round change message.
func (m *Message) TryRoundChange() (*RoundChange, error) {
if m.roundChange != nil {
return m.roundChange, nil
}
if m.Code != MsgRoundChange {
return nil, fmt.Errorf("expected round change message, received code: %d", m.Code)
}
if err := m.DecodeMessage(); err != nil {
return nil, err
}
return m.roundChange, nil
}
// Prepare returns round change if this is a round change message.
func (m *Message) RoundChange() *RoundChange {
return m.roundChange
}
// QueryEnode returns query enode data if this is a query enode message.
func (m *Message) QueryEnodeMsg() *QueryEnodeData {
return m.queryEnode
}
// ForwardMessage returns forward message if this is a forward message.
func (m *Message) ForwardMessage() *ForwardMessage {
return m.forwardMessage
}
// EnodeCertificate returns the enode certificate if this is an enode
// certificate message
func (m *Message) EnodeCertificate() *EnodeCertificate {
return m.enodeCertificate
}
// VersionCertificates returns the version certificate entries if this is a
// version certificates message.
func (m *Message) VersionCertificates() []*VersionCertificate {
return m.versionCertificates
}
// ValEnodesShareData returns val enode share data if this is a val enodes share message.
func (m *Message) ValEnodesShareData() *ValEnodesShareData {
return m.valEnodeShareData
}
func (m *Message) Copy() *Message {
return &Message{
Code: m.Code,
Msg: append(m.Msg[:0:0], m.Msg...),
Address: m.Address,
Signature: append(m.Signature[:0:0], m.Signature...),
}
}
// MapMessagesToSenders map a list of Messages to the list of the sender addresses
func MapMessagesToSenders(messages []Message) []common.Address {
returnList := make([]common.Address, len(messages))
for i, ms := range messages {
returnList[i] = ms.Address
}
return returnList
}
// ## EnodeCertificate ######################################################################
// NewValEnodesShareMessage constructs a Message instance with the given sender
// and enodeCertificate. Both the enodeCertificate instance and the serialized
// bytes of enodeCertificate are part of the returned Message.
func NewEnodeCeritifcateMessage(enodeCertificate *EnodeCertificate, sender common.Address) *Message {
message := &Message{
Address: sender,
Code: EnodeCertificateMsg,
enodeCertificate: enodeCertificate,
}
setMessageBytes(message, enodeCertificate)
return message
}
type EnodeCertificate struct {
EnodeURL string
Version uint
}
// EncodeRLP serializes ec into the Ethereum RLP format.
func (ec *EnodeCertificate) EncodeRLP(w io.Writer) error {
return rlp.Encode(w, []interface{}{ec.EnodeURL, ec.Version})
}
// DecodeRLP implements rlp.Decoder, and load the ec fields from a RLP stream.
func (ec *EnodeCertificate) DecodeRLP(s *rlp.Stream) error {
var msg struct {
EnodeURL string
Version uint
}
if err := s.Decode(&msg); err != nil {
return err
}
ec.EnodeURL, ec.Version = msg.EnodeURL, msg.Version
return nil
}
// ## EnodeCertMsg ######################################################################
type EnodeCertMsg struct {
Msg *Message
DestAddresses []common.Address
}
// ## AddressEntry ######################################################################
// AddressEntry is an entry for the valEnodeTable.
type AddressEntry struct {
Address common.Address
PublicKey *ecdsa.PublicKey
Node *enode.Node
Version uint
HighestKnownVersion uint
NumQueryAttemptsForHKVersion uint
LastQueryTimestamp *time.Time
}
func (ae *AddressEntry) String() string {
var nodeString string
if ae.Node != nil {
nodeString = ae.Node.String()
}
return fmt.Sprintf("{address: %v, enodeURL: %v, version: %v, highestKnownVersion: %v, numQueryAttempsForHKVersion: %v, LastQueryTimestamp: %v}", ae.Address.String(), nodeString, ae.Version, ae.HighestKnownVersion, ae.NumQueryAttemptsForHKVersion, ae.LastQueryTimestamp)
}
// Implement RLP Encode/Decode interface
type AddressEntryRLP struct {
Address common.Address
CompressedPublicKey []byte
EnodeURL string
Version uint
HighestKnownVersion uint
NumQueryAttemptsForHKVersion uint
LastQueryTimestamp []byte
}
// EncodeRLP serializes AddressEntry into the Ethereum RLP format.
func (ae *AddressEntry) EncodeRLP(w io.Writer) error {
var nodeString string
if ae.Node != nil {
nodeString = ae.Node.String()
}
var publicKeyBytes []byte
if ae.PublicKey != nil {
publicKeyBytes = crypto.CompressPubkey(ae.PublicKey)
}
var lastQueryTimestampBytes []byte
if ae.LastQueryTimestamp != nil {
var err error
lastQueryTimestampBytes, err = ae.LastQueryTimestamp.MarshalBinary()
if err != nil {
return err
}
}
return rlp.Encode(w, AddressEntryRLP{Address: ae.Address,
CompressedPublicKey: publicKeyBytes,
EnodeURL: nodeString,
Version: ae.Version,
HighestKnownVersion: ae.HighestKnownVersion,
NumQueryAttemptsForHKVersion: ae.NumQueryAttemptsForHKVersion,
LastQueryTimestamp: lastQueryTimestampBytes})
}
// DecodeRLP implements rlp.Decoder, and load the AddressEntry fields from a RLP stream.
func (ae *AddressEntry) DecodeRLP(s *rlp.Stream) error {
var entry AddressEntryRLP
var err error
if err := s.Decode(&entry); err != nil {
return err
}
var node *enode.Node
if len(entry.EnodeURL) > 0 {
node, err = enode.ParseV4(entry.EnodeURL)
if err != nil {
return err
}
}
var publicKey *ecdsa.PublicKey
if len(entry.CompressedPublicKey) > 0 {
publicKey, err = crypto.DecompressPubkey(entry.CompressedPublicKey)
if err != nil {
return err
}
}
lastQueryTimestamp := &time.Time{}
if len(entry.LastQueryTimestamp) > 0 {
err := lastQueryTimestamp.UnmarshalBinary(entry.LastQueryTimestamp)