[test] State trans unit test (#3043)

* completing create-validator tests

generalizing create validator tests, started with edit validator tests

one round completed before major refactor

* [test] finished coding test TestCheckDuplicateFields

* [test] finished debug TestCheckDuplicateFields

* [test] Added TestDescription_EnsureLength

* [test] added test in validator_test.go TestUpdateDescription

* [test] Added test TestComputed_String

* [test] refactored TestValidatorSanityCheck and added some message in error message returned from sanity check

* [test] removed test index for debugging

* [test] Added test TestValidatorWrapper_SanityCheck. Added value check for TestMarshalUnmarshalValidator. Fixed rlp usage defect in UnmarshalValidator

* [test] added test TestVerifyBLSKeys

* [test] added test TestContainsHarmonyBLSKeys

* [test] added test TestCreateValidatorFromNewMsg

* [test] fixed some tests errors

* [test] added test TestUpdateValidatorFromEditMsg, last editted the test file, finished testing validator_test.go

* [staking] added numeric.Dec.Copy method

* [staking] added CommissionRates.Copy

* [staking] add nil case handle to copy method and related test case

* [test] added nil case for commissionRates.Copy test

* [staking] finished CreateValidator.Copy and related test case

* [staking] added EditValidator.Copy method and related test case

* [test] added zero test cases for Copy method

* [staking] implemented Delegate.Copy and related unit test case

* [staking] added Undelegate.Copy and CollectReward.Copy method. Implemented corresponding test cases

* [test] added two more simple unit tests

* [test] solving the merge conflict with deep copy fix

* [test] added schedule for sharding

* [test] refactored double_sign_test.go

* [test] comment out all test cases for now.

* [test] added record Copy method for testing

* [test] added the first test case in TestVerify

* [test] finished test TestVerify

* [test] Added test TestVerify, TestApplySlashRate, TestSetDifference

* [test] half through TestDelegatorSlashApply

* [test] fix the problem cause by unsafe usage of big.Int

* [staking] added the copy methods to validatorWrapper

* [test] added test cases for copy method for staking/validatorWrapper

* [test] added test case TestApply

* [test] added test case TestRate

* [test] fix the golint errors

* [test] removed commented out unit test code

* [test] remote the empty line in imports

* [test] moved copy methods to stake_testing module

* [test] removed usage of interface stateDB

* [test] removed empty lines in imports

* [test] fixed golint package name issues

* [test] removed a todo when writing code

* [test] moved record.Copy to staking/slash/test

* [test] add some changes

* [test] added prototypes in staketest module

* [test] fix the golint issue in staketest

* [test] make prototype more beautiful

* [test] refactored test TestCheckDuplicateFields

* [test] add createValidator test data

* [test] added positive test case for VerifyAndCreateValidatorFromMsg

* [test] added create validator test

* [test] added the positive test case for TestVerifyAndEditValidatorFromMsg

* [test] added the tests case TestVerifyAndEditValidatorFromMsg

* [test] fix one of the error is not triggered as expected

* [test] more changes in test

* [test] fix the positive test data for TestVerifyAndDelegateFromMsg

* [test] Fixed two comment golint errors

* [test] added delegate tests

* [test] added a make function. WIP

* [test] added undelegate positive test

* [test] added negative test cases for undelegate

* [test] added positive test. not passed. Need to add assert method in test suites

* [test] added equal function to check Validator Equality

* [test] added equals for staketest

* [test] replaced deep equal with new equal methods:

* [test] removed unused codes

* [test] Finishing touch

* [test] fix comment golint issue

* [test] removed dead code in staking_verifier_test.go

Co-authored-by: Ganesha Upadhyaya <ganeshrvce@gmail.com>
pull/3060/head
Jacky Wang 5 years ago committed by GitHub
parent 1a6816c02b
commit 99fb897bb4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 2
      core/block_validator.go
  2. 6
      core/blockchain.go
  3. 7
      core/staking_verifier.go
  4. 2055
      core/staking_verifier_test.go
  5. 14
      core/tx_pool_test.go
  6. 2
      staking/slash/double-sign_test.go
  7. 4
      staking/types/test/copy.go
  8. 4
      staking/types/test/copy_test.go
  9. 209
      staking/types/test/equal.go
  10. 37
      staking/types/test/equal_test.go
  11. 118
      staking/types/test/prototype.go
  12. 79
      staking/types/test/prototype_test.go

@ -36,7 +36,7 @@ import (
// BlockValidator is responsible for validating block headers, uncles and // BlockValidator is responsible for validating block headers, uncles and
// processed state. // processed state.
// //
// BlockValidator implements Validator. // BlockValidator implements validator.
type BlockValidator struct { type BlockValidator struct {
config *params.ChainConfig // Chain configuration options config *params.ChainConfig // Chain configuration options
bc *BlockChain // Canonical block chain bc *BlockChain // Canonical block chain

@ -102,9 +102,9 @@ type CacheConfig struct {
// block. The Blockchain manages chain imports, reverts, chain reorganisations. // block. The Blockchain manages chain imports, reverts, chain reorganisations.
// //
// Importing blocks in to the block chain happens according to the set of rules // Importing blocks in to the block chain happens according to the set of rules
// defined by the two stage Validator. Processing of blocks is done using the // defined by the two stage validator. Processing of blocks is done using the
// Processor which processes the included transaction. The validation of the state // Processor which processes the included transaction. The validation of the state
// is done in the second part of the Validator. Failing results in aborting of // is done in the second part of the validator. Failing results in aborting of
// the import. // the import.
// //
// The BlockChain also helps in returning blocks from **any** chain included // The BlockChain also helps in returning blocks from **any** chain included
@ -170,7 +170,7 @@ type BlockChain struct {
} }
// NewBlockChain returns a fully initialised block chain using information // NewBlockChain returns a fully initialised block chain using information
// available in the database. It initialises the default Ethereum Validator and // available in the database. It initialises the default Ethereum validator and
// Processor. // Processor.
func NewBlockChain( func NewBlockChain(
db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig, db ethdb.Database, cacheConfig *CacheConfig, chainConfig *params.ChainConfig,

@ -111,9 +111,8 @@ func VerifyAndCreateValidatorFromMsg(
wrapper.Delegations = []staking.Delegation{ wrapper.Delegations = []staking.Delegation{
staking.NewDelegation(v.Address, msg.Amount), staking.NewDelegation(v.Address, msg.Amount),
} }
zero := big.NewInt(0) wrapper.Counters.NumBlocksSigned = big.NewInt(0)
wrapper.Counters.NumBlocksSigned = zero wrapper.Counters.NumBlocksToSign = big.NewInt(0)
wrapper.Counters.NumBlocksToSign = zero
wrapper.BlockReward = big.NewInt(0) wrapper.BlockReward = big.NewInt(0)
maxBLSKeyAllowed := shard.ExternalSlotsAvailableForEpoch(epoch) / 3 maxBLSKeyAllowed := shard.ExternalSlotsAvailableForEpoch(epoch) / 3
if err := wrapper.SanityCheck(maxBLSKeyAllowed); err != nil { if err := wrapper.SanityCheck(maxBLSKeyAllowed); err != nil {
@ -167,7 +166,7 @@ func VerifyAndEditValidatorFromMsg(
snapshotValidator, err := chainContext.ReadValidatorSnapshot(wrapper.Address) snapshotValidator, err := chainContext.ReadValidatorSnapshot(wrapper.Address)
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "Validator snapshot not found.") return nil, errors.WithMessage(err, "validator snapshot not found.")
} }
rateAtBeginningOfEpoch := snapshotValidator.Validator.Rate rateAtBeginningOfEpoch := snapshotValidator.Validator.Rate

File diff suppressed because it is too large Load Diff

@ -116,12 +116,12 @@ func stakingCreateValidatorTransaction(key *ecdsa.PrivateKey) (*staking.StakingT
MaxRate: maxRate, MaxRate: maxRate,
MaxChangeRate: maxChangeRate, MaxChangeRate: maxChangeRate,
}, },
MinSelfDelegation: tenK, MinSelfDelegation: tenKOnes,
MaxTotalDelegation: twelveK, MaxTotalDelegation: twelveKOnes,
ValidatorAddress: crypto.PubkeyToAddress(key.PublicKey), ValidatorAddress: crypto.PubkeyToAddress(key.PublicKey),
SlotPubKeys: []shard.BLSPublicKey{pub}, SlotPubKeys: []shard.BLSPublicKey{pub},
SlotKeySigs: []shard.BLSSignature{sig}, SlotKeySigs: []shard.BLSSignature{sig},
Amount: tenK, Amount: tenKOnes,
} }
} }
@ -374,8 +374,8 @@ func TestErrorSink(t *testing.T) {
t.Error("expected errored transaction in tx pool") t.Error("expected errored transaction in tx pool")
} }
pool.currentState.SetBalance(from, twelveK) pool.currentState.SetBalance(from, twelveKOnes)
pool.currentState.SetBalance(fromStx, twelveK) pool.currentState.SetBalance(fromStx, twelveKOnes)
if err := pool.AddRemote(tx); err != nil { if err := pool.AddRemote(tx); err != nil {
t.Error("expected successful transaction got", err) t.Error("expected successful transaction got", err)
} }
@ -403,7 +403,7 @@ func TestCreateValidatorTransaction(t *testing.T) {
t.Errorf("cannot create new staking transaction, %v\n", err) t.Errorf("cannot create new staking transaction, %v\n", err)
} }
senderAddr, _ := stx.SenderAddress() senderAddr, _ := stx.SenderAddress()
pool.currentState.AddBalance(senderAddr, tenK) pool.currentState.AddBalance(senderAddr, tenKOnes)
// Add additional create validator tx cost // Add additional create validator tx cost
pool.currentState.AddBalance(senderAddr, cost) pool.currentState.AddBalance(senderAddr, cost)
@ -429,7 +429,7 @@ func TestMixedTransactions(t *testing.T) {
t.Errorf("cannot create new staking transaction, %v\n", err) t.Errorf("cannot create new staking transaction, %v\n", err)
} }
stxAddr, _ := stx.SenderAddress() stxAddr, _ := stx.SenderAddress()
pool.currentState.AddBalance(stxAddr, tenK) pool.currentState.AddBalance(stxAddr, tenKOnes)
// Add additional create validator tx cost // Add additional create validator tx cost
pool.currentState.AddBalance(stxAddr, cost) pool.currentState.AddBalance(stxAddr, cost)

@ -780,7 +780,7 @@ func makeVoteData(kp blsKeyPair, block *types.Block) Vote {
} }
func makeTestAddress(item interface{}) common.Address { func makeTestAddress(item interface{}) common.Address {
s := fmt.Sprintf("harmony.one.%s", item) s := fmt.Sprintf("harmony.one.%v", item)
return common.BytesToAddress([]byte(s)) return common.BytesToAddress([]byte(s))
} }

@ -8,8 +8,8 @@ import (
) )
// CopyValidatorWrapper deep copies staking.ValidatorWrapper // CopyValidatorWrapper deep copies staking.ValidatorWrapper
func CopyValidatorWrapper(w *staking.ValidatorWrapper) *staking.ValidatorWrapper { func CopyValidatorWrapper(w staking.ValidatorWrapper) staking.ValidatorWrapper {
cp := &staking.ValidatorWrapper{ cp := staking.ValidatorWrapper{
Validator: CopyValidator(w.Validator), Validator: CopyValidator(w.Validator),
Delegations: CopyDelegations(w.Delegations), Delegations: CopyDelegations(w.Delegations),
} }

@ -27,9 +27,9 @@ func TestCopyValidatorWrapper(t *testing.T) {
{staking.ValidatorWrapper{}}, {staking.ValidatorWrapper{}},
} }
for i, test := range tests { for i, test := range tests {
cp := CopyValidatorWrapper(&test.w) cp := CopyValidatorWrapper(test.w)
if err := assertValidatorWrapperDeepCopy(*cp, test.w); err != nil { if err := assertValidatorWrapperDeepCopy(cp, test.w); err != nil {
t.Errorf("Test %v: %v", i, err) t.Errorf("Test %v: %v", i, err)
} }
} }

@ -0,0 +1,209 @@
package staketest
import (
"fmt"
"math/big"
"github.com/harmony-one/harmony/numeric"
"github.com/harmony-one/harmony/shard"
staking "github.com/harmony-one/harmony/staking/types"
)
// CheckValidatorWrapperEqual checks the equality of staking.ValidatorWrapper. If not equal, an
// error is returned. Note nil pointer is treated as zero in this compare function.
func CheckValidatorWrapperEqual(w1, w2 staking.ValidatorWrapper) error {
if err := checkValidatorWrapperEqual(w1, w2); err != nil {
return fmt.Errorf("wrapper%v", err)
}
return nil
}
// CheckValidatorEqual checks the equality of validator. If not equal, an
// error is returned. Note nil pointer is treated as zero in this compare function.
func CheckValidatorEqual(v1, v2 staking.Validator) error {
if err := checkValidatorEqual(v1, v2); err != nil {
return fmt.Errorf("validator%v", err)
}
return nil
}
func checkValidatorWrapperEqual(w1, w2 staking.ValidatorWrapper) error {
if err := checkValidatorEqual(w1.Validator, w2.Validator); err != nil {
return fmt.Errorf(".Validator%v", err)
}
if err := checkDelegationsEqual(w1.Delegations, w2.Delegations); err != nil {
return fmt.Errorf(".Delegations%v", err)
}
if err := checkBigIntEqual(w1.Counters.NumBlocksToSign, w2.Counters.NumBlocksToSign); err != nil {
return fmt.Errorf("..Counters.NumBlocksToSign %v", err)
}
if err := checkBigIntEqual(w1.Counters.NumBlocksSigned, w2.Counters.NumBlocksSigned); err != nil {
return fmt.Errorf("..Counters.NumBlocksSigned %v", err)
}
if err := checkBigIntEqual(w1.BlockReward, w2.BlockReward); err != nil {
return fmt.Errorf(".BlockReward %v", err)
}
return nil
}
func checkValidatorEqual(v1, v2 staking.Validator) error {
if v1.Address != v2.Address {
return fmt.Errorf(".Address not equal: %x / %x", v1.Address, v2.Address)
}
if err := checkPubKeysEqual(v1.SlotPubKeys, v2.SlotPubKeys); err != nil {
return fmt.Errorf(".SlotPubKeys%v", err)
}
if err := checkBigIntEqual(v1.LastEpochInCommittee, v2.LastEpochInCommittee); err != nil {
return fmt.Errorf(".LastEpochInCommittee %v", err)
}
if err := checkBigIntEqual(v1.MinSelfDelegation, v2.MinSelfDelegation); err != nil {
return fmt.Errorf(".MinSelfDelegation %v", err)
}
if err := checkBigIntEqual(v1.MaxTotalDelegation, v2.MaxTotalDelegation); err != nil {
return fmt.Errorf(".MaxTotalDelegation %v", err)
}
if v1.Status != v2.Status {
return fmt.Errorf(".Status not equal: %v / %v", v1.Status, v2.Status)
}
if err := checkCommissionEqual(v1.Commission, v2.Commission); err != nil {
return fmt.Errorf(".Commission%v", err)
}
if err := checkDescriptionEqual(v1.Description, v2.Description); err != nil {
return fmt.Errorf(".Description%v", err)
}
if err := checkBigIntEqual(v1.CreationHeight, v2.CreationHeight); err != nil {
return fmt.Errorf(".CreationHeight %v", err)
}
return nil
}
func checkDelegationsEqual(ds1, ds2 staking.Delegations) error {
if len(ds1) != len(ds2) {
return fmt.Errorf(".len not equal: %v / %v", len(ds1), len(ds2))
}
for i := range ds1 {
if err := checkDelegationEqual(ds1[i], ds2[i]); err != nil {
return fmt.Errorf("[%v]%v", i, err)
}
}
return nil
}
func checkDelegationEqual(d1, d2 staking.Delegation) error {
if d1.DelegatorAddress != d2.DelegatorAddress {
return fmt.Errorf(".DelegatorAddress not equal: %x / %x",
d1.DelegatorAddress, d2.DelegatorAddress)
}
if err := checkBigIntEqual(d1.Amount, d2.Amount); err != nil {
return fmt.Errorf(".Amount %v", err)
}
if err := checkBigIntEqual(d1.Reward, d2.Reward); err != nil {
return fmt.Errorf(".Reward %v", err)
}
if err := checkUndelegationsEqual(d1.Undelegations, d2.Undelegations); err != nil {
return fmt.Errorf(".Undelegations%v", err)
}
return nil
}
func checkUndelegationsEqual(uds1, uds2 staking.Undelegations) error {
if len(uds1) != len(uds2) {
return fmt.Errorf(".len not equal: %v / %v", len(uds1), len(uds2))
}
for i := range uds1 {
if err := checkUndelegationEqual(uds1[i], uds2[i]); err != nil {
return fmt.Errorf("[%v]%v", i, err)
}
}
return nil
}
func checkUndelegationEqual(ud1, ud2 staking.Undelegation) error {
if err := checkBigIntEqual(ud1.Amount, ud2.Amount); err != nil {
return fmt.Errorf(".Amount %v", err)
}
if err := checkBigIntEqual(ud1.Epoch, ud2.Epoch); err != nil {
return fmt.Errorf(".Epoch %v", err)
}
return nil
}
func checkPubKeysEqual(pubs1, pubs2 []shard.BLSPublicKey) error {
if len(pubs1) != len(pubs2) {
return fmt.Errorf(".len not equal: %v / %v", len(pubs1), len(pubs2))
}
for i := range pubs1 {
if pubs1[i] != pubs2[i] {
return fmt.Errorf("[%v] not equal: %x / %x", i, pubs1[i], pubs2[i])
}
}
return nil
}
func checkDescriptionEqual(d1, d2 staking.Description) error {
if d1.Name != d2.Name {
return fmt.Errorf(".Name not equal: %v / %v", d1.Name, d2.Name)
}
if d1.Identity != d2.Identity {
return fmt.Errorf(".Identity not equal: %v / %v", d1.Identity, d2.Identity)
}
if d1.Website != d2.Website {
return fmt.Errorf(".Website not equal: %v / %v", d1.Website, d2.Website)
}
if d1.Details != d2.Details {
return fmt.Errorf(".Details not equal: %v / %v", d1.Details, d2.Details)
}
if d1.SecurityContact != d2.SecurityContact {
return fmt.Errorf(".SecurityContact not equal: %v / %v", d1.SecurityContact, d2.SecurityContact)
}
return nil
}
func checkCommissionEqual(c1, c2 staking.Commission) error {
if err := checkCommissionRateEqual(c1.CommissionRates, c2.CommissionRates); err != nil {
return fmt.Errorf(".CommissionRate%v", err)
}
if err := checkBigIntEqual(c1.UpdateHeight, c2.UpdateHeight); err != nil {
return fmt.Errorf(".UpdateHeight %v", err)
}
return nil
}
func checkCommissionRateEqual(cr1, cr2 staking.CommissionRates) error {
if err := checkDecEqual(cr1.Rate, cr2.Rate); err != nil {
return fmt.Errorf(".Rate %v", err)
}
if err := checkDecEqual(cr1.MaxChangeRate, cr2.MaxChangeRate); err != nil {
return fmt.Errorf(".MaxChangeRate %v", err)
}
if err := checkDecEqual(cr1.MaxRate, cr2.MaxRate); err != nil {
return fmt.Errorf(".MaxRate %v", err)
}
return nil
}
func checkDecEqual(d1, d2 numeric.Dec) error {
if d1.IsNil() {
d1 = numeric.ZeroDec()
}
if d2.IsNil() {
d2 = numeric.ZeroDec()
}
if !d1.Equal(d2) {
return fmt.Errorf("not equal: %v / %v", d1, d2)
}
return nil
}
func checkBigIntEqual(i1, i2 *big.Int) error {
if i1 == nil {
i1 = big.NewInt(0)
}
if i2 == nil {
i2 = big.NewInt(0)
}
if i1.Cmp(i2) != 0 {
return fmt.Errorf("not equal: %v / %v", i1, i2)
}
return nil
}

@ -0,0 +1,37 @@
package staketest
import (
"testing"
staking "github.com/harmony-one/harmony/staking/types"
)
func TestCheckValidatorWrapperEqual(t *testing.T) {
tests := []struct {
w1, w2 staking.ValidatorWrapper
}{
{vWrapperPrototype, vWrapperPrototype},
{makeZeroValidatorWrapper(), makeZeroValidatorWrapper()},
{staking.ValidatorWrapper{}, staking.ValidatorWrapper{}},
}
for i, test := range tests {
if err := CheckValidatorWrapperEqual(test.w1, test.w2); err != nil {
t.Errorf("Test %v: %v", i, err)
}
}
}
func TestCheckValidatorEqual(t *testing.T) {
tests := []struct {
v1, v2 staking.Validator
}{
{validatorPrototype, validatorPrototype},
{makeZeroValidator(), makeZeroValidator()},
{staking.Validator{}, staking.Validator{}},
}
for i, test := range tests {
if err := CheckValidatorEqual(test.v1, test.v2); err != nil {
t.Errorf("Test %v: %v", i, err)
}
}
}

@ -0,0 +1,118 @@
package staketest
import (
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/numeric"
"github.com/harmony-one/harmony/shard"
"github.com/harmony-one/harmony/staking/effective"
staking "github.com/harmony-one/harmony/staking/types"
)
var (
oneBig = big.NewInt(1e18)
tenKOnes = new(big.Int).Mul(big.NewInt(10000), oneBig)
twentyKOnes = new(big.Int).Mul(big.NewInt(20000), oneBig)
hundredKOnes = new(big.Int).Mul(big.NewInt(100000), oneBig)
// DefaultDelAmount is the default delegation amount
DefaultDelAmount = new(big.Int).Set(twentyKOnes)
// DefaultMinSelfDel is the default value of MinSelfDelegation
DefaultMinSelfDel = new(big.Int).Set(tenKOnes)
// DefaultMaxTotalDel is the default value of MaxTotalDelegation
DefaultMaxTotalDel = new(big.Int).Set(hundredKOnes)
)
var (
vWrapperPrototype = func() staking.ValidatorWrapper {
w := staking.ValidatorWrapper{
Validator: validatorPrototype,
Delegations: staking.Delegations{
staking.Delegation{
DelegatorAddress: validatorPrototype.Address,
Amount: DefaultDelAmount,
Reward: common.Big0,
Undelegations: staking.Undelegations{},
},
},
BlockReward: common.Big0,
}
w.Counters.NumBlocksToSign = common.Big0
w.Counters.NumBlocksSigned = common.Big0
return w
}()
validatorPrototype = staking.Validator{
Address: common.Address{},
SlotPubKeys: []shard.BLSPublicKey{shard.BLSPublicKey{}},
LastEpochInCommittee: common.Big0,
MinSelfDelegation: DefaultMinSelfDel,
MaxTotalDelegation: DefaultMaxTotalDel,
Status: effective.Active,
Commission: commission,
Description: description,
CreationHeight: common.Big0,
}
commissionRates = staking.CommissionRates{
Rate: numeric.NewDecWithPrec(5, 1),
MaxRate: numeric.NewDecWithPrec(9, 1),
MaxChangeRate: numeric.NewDecWithPrec(3, 1),
}
commission = staking.Commission{
CommissionRates: commissionRates,
UpdateHeight: common.Big0,
}
description = staking.Description{
Name: "SuperHero",
Identity: "YouWouldNotKnow",
Website: "Secret Website",
SecurityContact: "LicenseToKill",
Details: "blah blah blah",
}
)
// GetDefaultValidator return the default staking.Validator for testing
func GetDefaultValidator() staking.Validator {
return CopyValidator(validatorPrototype)
}
// GetDefaultValidatorWithAddr return the default staking.Validator with the
// given validator address and bls keys
func GetDefaultValidatorWithAddr(addr common.Address, pubs []shard.BLSPublicKey) staking.Validator {
v := CopyValidator(validatorPrototype)
v.Address = addr
if pubs != nil {
v.SlotPubKeys = make([]shard.BLSPublicKey, len(pubs))
copy(v.SlotPubKeys, pubs)
} else {
v.SlotPubKeys = nil
}
return v
}
// GetDefaultValidatorWrapper return the default staking.ValidatorWrapper for testing
func GetDefaultValidatorWrapper() staking.ValidatorWrapper {
return CopyValidatorWrapper(vWrapperPrototype)
}
// GetDefaultValidatorWrapperWithAddr return the default staking.ValidatorWrapper
// with the given validator address and bls keys.
func GetDefaultValidatorWrapperWithAddr(addr common.Address, pubs []shard.BLSPublicKey) staking.ValidatorWrapper {
w := CopyValidatorWrapper(vWrapperPrototype)
w.Address = addr
if pubs != nil {
w.SlotPubKeys = make([]shard.BLSPublicKey, len(pubs))
copy(w.SlotPubKeys, pubs)
} else {
w.SlotPubKeys = nil
}
w.Delegations[0].DelegatorAddress = addr
return w
}

@ -0,0 +1,79 @@
package staketest
import (
"testing"
"github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/shard"
)
func TestGetDefaultValidator(t *testing.T) {
v := GetDefaultValidator()
if err := assertValidatorDeepCopy(v, validatorPrototype); err != nil {
t.Error(err)
}
}
func TestGetDefaultValidatorWrapper(t *testing.T) {
w := GetDefaultValidatorWrapper()
if err := assertValidatorWrapperDeepCopy(w, vWrapperPrototype); err != nil {
t.Error(err)
}
}
func TestGetDefaultValidatorWithAddr(t *testing.T) {
tests := []struct {
addr common.Address
keys []shard.BLSPublicKey
}{
{
addr: common.BigToAddress(common.Big1),
keys: []shard.BLSPublicKey{{1}, {}},
},
{
addr: common.Address{},
keys: make([]shard.BLSPublicKey, 0),
},
{},
}
for i, test := range tests {
v := GetDefaultValidatorWithAddr(test.addr, test.keys)
exp := CopyValidator(validatorPrototype)
exp.Address = test.addr
exp.SlotPubKeys = test.keys
if err := assertValidatorDeepCopy(v, exp); err != nil {
t.Errorf("Test %v: %v", i, err)
}
}
}
func TestGetDefaultValidatorWrapperWithAddr(t *testing.T) {
tests := []struct {
addr common.Address
keys []shard.BLSPublicKey
}{
{
addr: common.BigToAddress(common.Big1),
keys: []shard.BLSPublicKey{{1}, {}},
},
{
addr: common.Address{},
keys: make([]shard.BLSPublicKey, 0),
},
{},
}
for i, test := range tests {
v := GetDefaultValidatorWrapperWithAddr(test.addr, test.keys)
exp := CopyValidatorWrapper(vWrapperPrototype)
exp.Address = test.addr
exp.SlotPubKeys = test.keys
exp.Delegations[0].DelegatorAddress = test.addr
if err := assertValidatorWrapperDeepCopy(v, exp); err != nil {
t.Errorf("Test %v: %v", i, err)
}
}
}
Loading…
Cancel
Save