add helper functions (#9)

This commit is contained in:
David Hill 2020-05-15 02:48:22 -05:00 committed by GitHub
parent 57dfc1ed6d
commit c371f1983b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 77 additions and 0 deletions

42
helpers.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/dcrutil/v3"
)
func currentVoteVersion(params *chaincfg.Params) uint32 {
var latestVersion uint32
for version := range params.Deployments {
if latestVersion < version {
latestVersion = version
}
}
return latestVersion
}
// isValidVoteBits returns an error if voteBits are not valid for agendas
func isValidVoteBits(params *chaincfg.Params, voteVersion uint32, voteBits uint16) bool {
if !dcrutil.IsFlagSet16(voteBits, dcrutil.BlockValid) {
return false
}
voteBits &= ^uint16(dcrutil.BlockValid)
var availVoteBits uint16
for _, vote := range params.Deployments[voteVersion] {
availVoteBits |= vote.Vote.Mask
isValid := false
maskedBits := voteBits & vote.Vote.Mask
for _, c := range vote.Vote.Choices {
if c.Bits == maskedBits {
isValid = true
break
}
}
if !isValid {
return false
}
}
return true
}

35
helpers_test.go Normal file
View File

@ -0,0 +1,35 @@
package main
import (
"testing"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/dcrutil/v3"
)
func TestVoteBits(t *testing.T) {
var tests = []struct {
voteBits uint16
isValid bool
}{
{0, false},
{dcrutil.BlockValid, true},
{dcrutil.BlockValid | 0x0002, true},
{dcrutil.BlockValid | 0x0003, true},
{dcrutil.BlockValid | 0x0004, true},
{dcrutil.BlockValid | 0x0005, true},
{dcrutil.BlockValid | 0x0006, false},
{dcrutil.BlockValid | 0x0007, false},
{dcrutil.BlockValid | 0x0008, true},
}
params := chaincfg.MainNetParams()
voteVersion := currentVoteVersion(params)
for _, test := range tests {
isValid := isValidVoteBits(params, voteVersion, test.voteBits)
if isValid != test.isValid {
t.Fatalf("isValidVoteBits failed for votebits '%d': want %v, got %v",
test.voteBits, test.isValid, isValid)
}
}
}