-
Notifications
You must be signed in to change notification settings - Fork 6
/
message.go
109 lines (93 loc) · 2.3 KB
/
message.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
package main
import (
"bytes"
"encoding/json"
"errors"
"github.com/tinychain/algorand/common"
)
const (
// message type
VOTE = iota
BLOCK_PROPOSAL
FORK_PROPOSAL
BLOCK
)
type VoteMessage struct {
Signature []byte `json:"signature"`
Round uint64 `json:"round"`
Step int `json:"step"`
VRF []byte `json:"vrf"`
Proof []byte `json:"proof"`
ParentHash common.Hash `json:"parentHash"`
Hash common.Hash `json:"hash"`
}
func (v *VoteMessage) Serialize() ([]byte, error) {
return json.Marshal(v)
}
func (v *VoteMessage) Deserialize(data []byte) error {
return json.Unmarshal(data, v)
}
func (v *VoteMessage) VerifySign() error {
pubkey := v.RecoverPubkey()
data := bytes.Join([][]byte{
common.Uint2Bytes(v.Round),
common.Uint2Bytes(uint64(v.Step)),
v.VRF,
v.Proof,
v.ParentHash.Bytes(),
v.Hash.Bytes(),
}, nil)
return pubkey.VerifySign(data, v.Signature)
}
func (v *VoteMessage) Sign(priv *PrivateKey) ([]byte, error) {
data := bytes.Join([][]byte{
common.Uint2Bytes(v.Round),
common.Uint2Bytes(uint64(v.Step)),
v.VRF,
v.Proof,
v.ParentHash.Bytes(),
v.Hash.Bytes(),
}, nil)
sign, err := priv.Sign(data)
if err != nil {
return nil, err
}
v.Signature = sign
return sign, nil
}
func (v *VoteMessage) RecoverPubkey() *PublicKey {
return recoverPubkey(v.Signature)
}
type Proposal struct {
Round uint64 `json:"round"`
Hash common.Hash `json:"hash"`
Prior []byte `json:"prior"`
VRF []byte `json:"vrf"` // vrf of user's sortition hash
Proof []byte `json:"proof"`
Pubkey []byte `json:"public_key"`
}
func (b *Proposal) Serialize() ([]byte, error) {
return json.Marshal(b)
}
func (b *Proposal) Deserialize(data []byte) error {
return json.Unmarshal(data, b)
}
func (b *Proposal) PublicKey() *PublicKey {
return &PublicKey{b.Pubkey}
}
func (b *Proposal) Address() common.Address {
return common.BytesToAddress(b.Pubkey)
}
func (b *Proposal) Verify(weight uint64, m []byte) error {
// verify vrf
pubkey := b.PublicKey()
if err := pubkey.VerifyVRF(b.Proof, m); err != nil {
return err
}
// verify priority
subusers := subUsers(expectedBlockProposers, weight, b.VRF)
if bytes.Compare(maxPriority(b.VRF, subusers), b.Prior) != 0 {
return errors.New("max priority mismatch")
}
return nil
}