validator.gno
2.01 Kb · 81 lines
1package tendermint
2
3import (
4 "bytes"
5 "encoding/base64"
6
7 "gno.land/p/aib/encoding/proto"
8 "gno.land/p/aib/merkle"
9)
10
11type ValidatorSet struct {
12 Validators []*Validator
13 Proposer *Validator
14 TotalVotingPower int64
15}
16
17func NewValset(vals ...*Validator) *ValidatorSet {
18 var total int64
19 for _, v := range vals {
20 total += v.VotingPower
21 }
22 return &ValidatorSet{
23 Validators: vals,
24 Proposer: vals[0],
25 TotalVotingPower: total,
26 }
27}
28
29func (vals ValidatorSet) Hash() []byte {
30 bzs := make([][]byte, len(vals.Validators))
31 for i, val := range vals.Validators {
32 bzs[i] = val.Bytes()
33 }
34 return merkle.HashFromByteSlices(bzs)
35}
36
37// GetByAddress returns an index of the validator with address and validator
38// itself (copy) if found. Otherwise, -1 and nil are returned.
39func (vals *ValidatorSet) GetByAddress(address []byte) (index int32, val *Validator) {
40 for idx, val := range vals.Validators {
41 if bytes.Equal(val.Address, address) {
42 return int32(idx), val
43 }
44 }
45 return -1, nil
46}
47
48type Validator struct {
49 Address []byte
50 PubKey []byte
51 VotingPower int64
52 ProposerPriority int64
53}
54
55func NewValidator(addr, pubkey string, vp int64) *Validator {
56 addrBz, err := base64.StdEncoding.DecodeString(addr)
57 if err != nil {
58 panic(err)
59 }
60 pubkeyBz, err := base64.StdEncoding.DecodeString(pubkey)
61 if err != nil {
62 panic(err)
63 }
64 return &Validator{
65 Address: addrBz,
66 PubKey: pubkeyBz,
67 VotingPower: vp,
68 }
69}
70
71// Bytes computes the unique encoding of a validator with a given voting power.
72// These are the bytes that gets hashed in consensus. It excludes address as
73// its redundant with the pubkey.This also excludes ProposerPriority which
74// changes every round.
75// Proto ref: https://buf.build/tendermint/tendermint/docs/main:tendermint.types#tendermint.types.SimpleValidator
76func (v Validator) Bytes() (bz []byte) {
77 pkBz := proto.AppendLengthDelimited(nil, 1, v.PubKey)
78 bz = proto.AppendLengthDelimited(bz, 1, pkBz)
79 bz = proto.AppendVarint(bz, 2, uint64(v.VotingPower))
80 return
81}