Move ShardState et al from ./core/types to ./shard

pull/1498/head
Eugene Kim 5 years ago
parent e1ae274649
commit b874e65126
  1. 7
      api/proto/node/node.go
  2. 8
      api/service/explorer/service.go
  3. 3
      api/service/explorer/storage.go
  4. 15
      api/service/explorer/storage_test.go
  5. 9
      consensus/consensus.go
  6. 3
      consensus/engine/consensus_engine.go
  7. 4
      contracts/structs/structs.go
  8. 11
      core/blockchain.go
  9. 3
      core/chain_makers.go
  10. 3
      core/genesis.go
  11. 5
      core/rawdb/accessors_chain.go
  12. 44
      core/resharding.go
  13. 25
      core/resharding_test.go
  14. 7
      core/types/block.go
  15. 3
      node/node.go
  16. 10
      node/node_genesis.go
  17. 17
      node/node_handler.go
  18. 4
      node/node_newblock.go
  19. 5
      node/staking.go
  20. 2
      shard/shard_state.go
  21. 2
      shard/shard_state_test.go

@ -13,6 +13,7 @@ import (
"github.com/harmony-one/harmony/api/proto"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
// MessageType is to indicate the specific type of message under Node category
@ -158,7 +159,7 @@ func ConstructCrossLinkHeadersMessage(headers []*types.Header) []byte {
}
// ConstructEpochShardStateMessage contructs epoch shard state message
func ConstructEpochShardStateMessage(epochShardState types.EpochShardState) []byte {
func ConstructEpochShardStateMessage(epochShardState shard.EpochShardState) []byte {
byteBuffer := bytes.NewBuffer([]byte{byte(proto.Node)})
byteBuffer.WriteByte(byte(ShardState))
@ -172,8 +173,8 @@ func ConstructEpochShardStateMessage(epochShardState types.EpochShardState) []by
}
// DeserializeEpochShardStateFromMessage deserializes the shard state Message from bytes payload
func DeserializeEpochShardStateFromMessage(payload []byte) (*types.EpochShardState, error) {
epochShardState := new(types.EpochShardState)
func DeserializeEpochShardStateFromMessage(payload []byte) (*shard.EpochShardState, error) {
epochShardState := new(shard.EpochShardState)
r := bytes.NewBuffer(payload)
decoder := gob.NewDecoder(r)

@ -17,6 +17,7 @@ import (
libp2p_peer "github.com/libp2p/go-libp2p-peer"
"github.com/harmony-one/bls/ffi/go/bls"
msg_pb "github.com/harmony-one/harmony/api/proto/message"
"github.com/harmony-one/harmony/core/types"
bls2 "github.com/harmony-one/harmony/crypto/bls"
@ -25,6 +26,7 @@ import (
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/p2p"
"github.com/harmony-one/harmony/shard"
)
// Constants for explorer service.
@ -201,7 +203,7 @@ func (s *Service) GetExplorerBlocks(w http.ResponseWriter, r *http.Request) {
accountBlocks := s.ReadBlocksFromDB(fromInt, toInt)
curEpoch := int64(-1)
committee := &types.Committee{}
committee := &shard.Committee{}
for id, accountBlock := range accountBlocks {
if id == 0 || id == len(accountBlocks)-1 || accountBlock == nil {
continue
@ -209,7 +211,7 @@ func (s *Service) GetExplorerBlocks(w http.ResponseWriter, r *http.Request) {
block := NewBlock(accountBlock, id+fromInt-1)
if int64(block.Epoch) > curEpoch {
if bytes, err := db.Get([]byte(GetCommitteeKey(uint32(s.ShardID), block.Epoch))); err == nil {
committee = &types.Committee{}
committee = &shard.Committee{}
if err = rlp.DecodeBytes(bytes, committee); err != nil {
utils.Logger().Warn().Err(err).Msg("cannot read committee for new epoch")
}
@ -367,7 +369,7 @@ func (s *Service) GetCommittee(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(500)
return
}
committee := &types.Committee{}
committee := &shard.Committee{}
if err := rlp.DecodeBytes(bytes, committee); err != nil {
utils.Logger().Warn().Err(err).Msg("cannot decode committee data from DB")
w.WriteHeader(500)

@ -12,6 +12,7 @@ import (
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
// Constants for storage.
@ -125,7 +126,7 @@ func (storage *Storage) Dump(block *types.Block, height uint64) {
}
// DumpCommittee commits validators for shardNum and epoch.
func (storage *Storage) DumpCommittee(shardID uint32, epoch uint64, committee types.Committee) error {
func (storage *Storage) DumpCommittee(shardID uint32, epoch uint64, committee shard.Committee) error {
batch := storage.db.NewBatch()
// Store committees.
committeeData, err := rlp.EncodeToBytes(committee)

@ -9,7 +9,10 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/shard"
"github.com/stretchr/testify/assert"
)
@ -82,14 +85,14 @@ func TestDumpCommittee(t *testing.T) {
assert.Nil(t, err, "should be nil")
err = blsPubKey2.DeserializeHexStr("02c8ff0b88f313717bc3a627d2f8bb172ba3ad3bb9ba3ecb8eed4b7c878653d3d4faf769876c528b73f343967f74a917")
assert.Nil(t, err, "should be nil")
BlsPublicKey1 := new(types.BlsPublicKey)
BlsPublicKey2 := new(types.BlsPublicKey)
BlsPublicKey1 := new(shard.BlsPublicKey)
BlsPublicKey2 := new(shard.BlsPublicKey)
BlsPublicKey1.FromLibBLSPublicKey(blsPubKey1)
BlsPublicKey2.FromLibBLSPublicKey(blsPubKey2)
nodeID1 := types.NodeID{EcdsaAddress: common.HexToAddress("52789f18a342da8023cc401e5d2b14a6b710fba9"), BlsPublicKey: *BlsPublicKey1}
nodeID2 := types.NodeID{EcdsaAddress: common.HexToAddress("7c41e0668b551f4f902cfaec05b5bdca68b124ce"), BlsPublicKey: *BlsPublicKey2}
nodeIDList := []types.NodeID{nodeID1, nodeID2}
committee := types.Committee{ShardID: uint32(0), NodeList: nodeIDList}
nodeID1 := shard.NodeID{EcdsaAddress: common.HexToAddress("52789f18a342da8023cc401e5d2b14a6b710fba9"), BlsPublicKey: *BlsPublicKey1}
nodeID2 := shard.NodeID{EcdsaAddress: common.HexToAddress("7c41e0668b551f4f902cfaec05b5bdca68b124ce"), BlsPublicKey: *BlsPublicKey2}
nodeIDList := []shard.NodeID{nodeID1, nodeID2}
committee := shard.Committee{ShardID: uint32(0), NodeList: nodeIDList}
shardID := uint32(0)
epoch := uint64(0)
ins := GetStorageInstance("1.1.1.1", "3333", true)

@ -20,6 +20,7 @@ import (
"github.com/harmony-one/harmony/internal/memprofiling"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/p2p"
"github.com/harmony-one/harmony/shard"
)
const (
@ -304,7 +305,7 @@ func New(host p2p.Host, ShardID uint32, leader p2p.Peer, blsPriKey *bls.SecretKe
// genesis accounts.
// When used for block reward, it rewards only foundational nodes.
type GenesisStakeInfoFinder struct {
byNodeKey map[types.BlsPublicKey][]*structs.StakeInfo
byNodeKey map[shard.BlsPublicKey][]*structs.StakeInfo
byAccount map[common.Address][]*structs.StakeInfo
}
@ -314,7 +315,7 @@ type GenesisStakeInfoFinder struct {
func (f *GenesisStakeInfoFinder) FindStakeInfoByNodeKey(
key *bls.PublicKey,
) []*structs.StakeInfo {
var pk types.BlsPublicKey
var pk shard.BlsPublicKey
if err := pk.FromLibBLSPublicKey(key); err != nil {
utils.Logger().Warn().Err(err).Msg("cannot convert BLS public key")
return nil
@ -337,13 +338,13 @@ func (f *GenesisStakeInfoFinder) FindStakeInfoByAccount(
// genesis nodes.
func NewGenesisStakeInfoFinder() (*GenesisStakeInfoFinder, error) {
f := &GenesisStakeInfoFinder{
byNodeKey: make(map[types.BlsPublicKey][]*structs.StakeInfo),
byNodeKey: make(map[shard.BlsPublicKey][]*structs.StakeInfo),
byAccount: make(map[common.Address][]*structs.StakeInfo),
}
for idx, account := range genesis.HarmonyAccounts {
pub := &bls.PublicKey{}
pub.DeserializeHexStr(account.BlsPublicKey)
var blsPublicKey types.BlsPublicKey
var blsPublicKey shard.BlsPublicKey
if err := blsPublicKey.FromLibBLSPublicKey(pub); err != nil {
return nil, ctxerror.New("cannot convert BLS public key",
"accountIndex", idx,

@ -8,6 +8,7 @@ import (
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/shard"
)
// ChainReader defines a small collection of methods needed to access the local
@ -33,7 +34,7 @@ type ChainReader interface {
GetBlock(hash common.Hash, number uint64) *types.Block
// ReadShardState retrieves sharding state given the epoch number.
ReadShardState(epoch *big.Int) (types.ShardState, error)
ReadShardState(epoch *big.Int) (shard.ShardState, error)
}
// Engine is an algorithm agnostic consensus engine.

@ -3,7 +3,7 @@ package structs
import (
"math/big"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/shard"
"github.com/ethereum/go-ethereum/common"
)
@ -22,7 +22,7 @@ type StakeInfoReturnValue struct {
// StakeInfo stores the staking information for a staker.
type StakeInfo struct {
Account common.Address
BlsPublicKey types.BlsPublicKey
BlsPublicKey shard.BlsPublicKey
BlockNum *big.Int
LockPeriodCount *big.Int // The number of locking period the token will be locked.
Amount *big.Int

@ -46,6 +46,7 @@ import (
"github.com/harmony-one/harmony/core/vm"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
var (
@ -1805,10 +1806,10 @@ func (bc *BlockChain) SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscript
}
// ReadShardState retrieves sharding state given the epoch number.
func (bc *BlockChain) ReadShardState(epoch *big.Int) (types.ShardState, error) {
func (bc *BlockChain) ReadShardState(epoch *big.Int) (shard.ShardState, error) {
cacheKey := string(epoch.Bytes())
if cached, ok := bc.shardStateCache.Get(cacheKey); ok {
shardState := cached.(types.ShardState)
shardState := cached.(shard.ShardState)
return shardState, nil
}
shardState, err := rawdb.ReadShardState(bc.db, epoch)
@ -1821,7 +1822,7 @@ func (bc *BlockChain) ReadShardState(epoch *big.Int) (types.ShardState, error) {
// WriteShardState saves the given sharding state under the given epoch number.
func (bc *BlockChain) WriteShardState(
epoch *big.Int, shardState types.ShardState,
epoch *big.Int, shardState shard.ShardState,
) error {
shardState = shardState.DeepCopy()
err := rawdb.WriteShardState(bc.db, epoch, shardState)
@ -1837,7 +1838,7 @@ func (bc *BlockChain) WriteShardState(
func (bc *BlockChain) WriteShardStateBytes(
epoch *big.Int, shardState []byte,
) error {
decodeShardState := types.ShardState{}
decodeShardState := shard.ShardState{}
if err := rlp.DecodeBytes(shardState, &decodeShardState); err != nil {
return err
}
@ -1897,7 +1898,7 @@ func (bc *BlockChain) GetVrfByNumber(number uint64) []byte {
func (bc *BlockChain) GetShardState(
epoch *big.Int,
stakeInfo *map[common.Address]*structs.StakeInfo,
) (types.ShardState, error) {
) (shard.ShardState, error) {
shardState, err := bc.ReadShardState(epoch)
if err == nil { // TODO ek – distinguish ErrNotFound
return shardState, err

@ -28,6 +28,7 @@ import (
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/core/vm"
"github.com/harmony-one/harmony/shard"
)
// BlockGen creates blocks for testing.
@ -263,4 +264,4 @@ func (cr *fakeChainReader) GetHeaderByNumber(number uint64) *types.Header
func (cr *fakeChainReader) GetHeaderByHash(hash common.Hash) *types.Header { return nil }
func (cr *fakeChainReader) GetHeader(hash common.Hash, number uint64) *types.Header { return nil }
func (cr *fakeChainReader) GetBlock(hash common.Hash, number uint64) *types.Block { return nil }
func (cr *fakeChainReader) ReadShardState(epoch *big.Int) (types.ShardState, error) { return nil, nil }
func (cr *fakeChainReader) ReadShardState(epoch *big.Int) (shard.ShardState, error) { return nil, nil }

@ -36,6 +36,7 @@ import (
"github.com/harmony-one/harmony/core/state"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
// no go:generate gencodec -type Genesis -field-override genesisSpecMarshaling -out gen_genesis.go
@ -56,7 +57,7 @@ type Genesis struct {
Coinbase common.Address `json:"coinbase"`
Alloc GenesisAlloc `json:"alloc" gencodec:"required"`
ShardStateHash common.Hash `json:"shardStateHash" gencodec:"required"`
ShardState types.ShardState `json:"shardState" gencodec:"required"`
ShardState shard.ShardState `json:"shardState" gencodec:"required"`
// These fields are used for consensus tests. Please don't use them
// in actual genesis blocks.

@ -27,6 +27,7 @@ import (
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
// Indicate whether the receipts corresponding to a blockHash is spent or not
@ -412,7 +413,7 @@ func FindCommonAncestor(db DatabaseReader, a, b *types.Header) *types.Header {
// ReadShardState retrieves sharding state.
func ReadShardState(
db DatabaseReader, epoch *big.Int,
) (shardState types.ShardState, err error) {
) (shardState shard.ShardState, err error) {
var data []byte
data, err = db.Get(shardStateKey(epoch))
if err != nil {
@ -430,7 +431,7 @@ func ReadShardState(
// WriteShardState stores sharding state into database.
func WriteShardState(
db DatabaseWriter, epoch *big.Int, shardState types.ShardState,
db DatabaseWriter, epoch *big.Int, shardState shard.ShardState,
) (err error) {
data, err := rlp.EncodeToBytes(shardState)
if err != nil {

@ -12,11 +12,11 @@ import (
"github.com/harmony-one/bls/ffi/go/bls"
"github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
shardingconfig "github.com/harmony-one/harmony/internal/configs/sharding"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
const (
@ -31,7 +31,7 @@ type ShardingState struct {
epoch uint64 // current epoch
rnd uint64 // random seed for resharding
numShards int // TODO ek – equal to len(shardState); remove this
shardState types.ShardState
shardState shard.ShardState
}
// sortedCommitteeBySize will sort shards by size
@ -46,7 +46,7 @@ func (ss *ShardingState) sortCommitteeBySize() {
}
// assignNewNodes add new nodes into the N/2 active committees evenly
func (ss *ShardingState) assignNewNodes(newNodeList []types.NodeID) {
func (ss *ShardingState) assignNewNodes(newNodeList []shard.NodeID) {
ss.sortCommitteeBySize()
numActiveShards := ss.numShards / 2
Shuffle(newNodeList)
@ -66,7 +66,7 @@ func (ss *ShardingState) assignNewNodes(newNodeList []types.NodeID) {
// cuckooResharding uses cuckoo rule to reshard X% of active committee(shards) into inactive committee(shards)
func (ss *ShardingState) cuckooResharding(percent float64) {
numActiveShards := ss.numShards / 2
kickedNodes := []types.NodeID{}
kickedNodes := []shard.NodeID{}
for i := range ss.shardState {
if i >= numActiveShards {
break
@ -96,12 +96,12 @@ func (ss *ShardingState) cuckooResharding(percent float64) {
}
// Reshard will first add new nodes into shards, then use cuckoo rule to reshard to get new shard state
func (ss *ShardingState) Reshard(newNodeList []types.NodeID, percent float64) {
func (ss *ShardingState) Reshard(newNodeList []shard.NodeID, percent float64) {
rand.Seed(int64(ss.rnd))
ss.sortCommitteeBySize()
// Take out and preserve leaders
leaders := []types.NodeID{}
leaders := []shard.NodeID{}
for i := 0; i < ss.numShards; i++ {
if len(ss.shardState[i].NodeList) > 0 {
leaders = append(leaders, ss.shardState[i].NodeList[0])
@ -119,15 +119,15 @@ func (ss *ShardingState) Reshard(newNodeList []types.NodeID, percent float64) {
utils.Logger().Error().Msg("Not enough leaders to assign to shards")
}
for i := 0; i < ss.numShards; i++ {
ss.shardState[i].NodeList = append([]types.NodeID{leaders[i]}, ss.shardState[i].NodeList...)
ss.shardState[i].NodeList = append([]shard.NodeID{leaders[i]}, ss.shardState[i].NodeList...)
}
}
// Shuffle will shuffle the list with result uniquely determined by seed, assuming there is no repeat items in the list
func Shuffle(list []types.NodeID) {
func Shuffle(list []shard.NodeID) {
// Sort to make sure everyone will generate the same with the same rand seed.
sort.Slice(list, func(i, j int) bool {
return types.CompareNodeIDByBLSKey(list[i], list[j]) == -1
return shard.CompareNodeIDByBLSKey(list[i], list[j]) == -1
})
rand.Shuffle(len(list), func(i, j int) {
list[i], list[j] = list[j], list[i]
@ -175,7 +175,7 @@ func GetShardingStateFromBlockChain(bc *BlockChain, epoch *big.Int) (*ShardingSt
func CalculateNewShardState(
bc *BlockChain, epoch *big.Int,
stakeInfo *map[common.Address]*structs.StakeInfo,
) (types.ShardState, error) {
) (shard.ShardState, error) {
if epoch.Cmp(big.NewInt(GenesisEpoch)) == 0 {
return GetInitShardState(), nil
}
@ -192,8 +192,8 @@ func CalculateNewShardState(
}
// UpdateShardingState remove the unstaked nodes and returns the newly staked node Ids.
func (ss *ShardingState) UpdateShardingState(stakeInfo *map[common.Address]*structs.StakeInfo) []types.NodeID {
oldBlsPublicKeys := make(map[types.BlsPublicKey]bool) // map of bls public keys
func (ss *ShardingState) UpdateShardingState(stakeInfo *map[common.Address]*structs.StakeInfo) []shard.NodeID {
oldBlsPublicKeys := make(map[shard.BlsPublicKey]bool) // map of bls public keys
for _, shard := range ss.shardState {
newNodeList := shard.NodeList
for _, nodeID := range shard.NodeList {
@ -208,11 +208,11 @@ func (ss *ShardingState) UpdateShardingState(stakeInfo *map[common.Address]*stru
shard.NodeList = newNodeList
}
newAddresses := []types.NodeID{}
newAddresses := []shard.NodeID{}
for addr, info := range *stakeInfo {
_, ok := oldBlsPublicKeys[info.BlsPublicKey]
if !ok {
newAddresses = append(newAddresses, types.NodeID{
newAddresses = append(newAddresses, shard.NodeID{
EcdsaAddress: addr,
BlsPublicKey: info.BlsPublicKey,
})
@ -230,12 +230,12 @@ func (ss *ShardingState) UpdateShardingState(stakeInfo *map[common.Address]*stru
var ShardingSchedule shardingconfig.Schedule = shardingconfig.MainnetSchedule
// GetInitShardState returns the initial shard state at genesis.
func GetInitShardState() types.ShardState {
func GetInitShardState() shard.ShardState {
return GetShardState(big.NewInt(GenesisEpoch))
}
// GetShardState returns the shard state based on epoch number
func GetShardState(epoch *big.Int) types.ShardState {
func GetShardState(epoch *big.Int) shard.ShardState {
utils.Logger().Info().Int64("epoch", epoch.Int64()).Msg("Get Shard State of Epoch.")
shardingConfig := ShardingSchedule.InstanceForEpoch(epoch)
shardNum := int(shardingConfig.NumShards())
@ -244,18 +244,18 @@ func GetShardState(epoch *big.Int) types.ShardState {
hmyAccounts := shardingConfig.HmyAccounts()
fnAccounts := shardingConfig.FnAccounts()
shardState := types.ShardState{}
shardState := shard.ShardState{}
for i := 0; i < shardNum; i++ {
com := types.Committee{ShardID: uint32(i)}
com := shard.Committee{ShardID: uint32(i)}
for j := 0; j < shardHarmonyNodes; j++ {
index := i + j*shardNum // The initial account to use for genesis nodes
pub := &bls.PublicKey{}
pub.DeserializeHexStr(hmyAccounts[index].BlsPublicKey)
pubKey := types.BlsPublicKey{}
pubKey := shard.BlsPublicKey{}
pubKey.FromLibBLSPublicKey(pub)
// TODO: directly read address for bls too
curNodeID := types.NodeID{
curNodeID := shard.NodeID{
EcdsaAddress: common2.ParseAddr(hmyAccounts[index].Address),
BlsPublicKey: pubKey,
}
@ -269,10 +269,10 @@ func GetShardState(epoch *big.Int) types.ShardState {
pub := &bls.PublicKey{}
pub.DeserializeHexStr(fnAccounts[index].BlsPublicKey)
pubKey := types.BlsPublicKey{}
pubKey := shard.BlsPublicKey{}
pubKey.FromLibBLSPublicKey(pub)
// TODO: directly read address for bls too
curNodeID := types.NodeID{
curNodeID := shard.NodeID{
EcdsaAddress: common2.ParseAddr(fnAccounts[index].Address),
BlsPublicKey: pubKey,
}

@ -8,7 +8,8 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/shard"
"github.com/stretchr/testify/assert"
)
@ -38,17 +39,17 @@ func init() {
copy(blsPubKey10[:], []byte("random key 10"))
}
func fakeGetInitShardState(numberOfShards, numOfNodes int) types.ShardState {
func fakeGetInitShardState(numberOfShards, numOfNodes int) shard.ShardState {
rand.Seed(int64(42))
shardState := types.ShardState{}
shardState := shard.ShardState{}
for i := 0; i < numberOfShards; i++ {
sid := uint32(i)
com := types.Committee{ShardID: sid}
com := shard.Committee{ShardID: sid}
for j := 0; j < numOfNodes; j++ {
nid := strconv.Itoa(int(rand.Int63()))
blsPubKey := [48]byte{}
copy(blsPubKey1[:], []byte(nid))
com.NodeList = append(com.NodeList, types.NodeID{
com.NodeList = append(com.NodeList, shard.NodeID{
EcdsaAddress: common.BytesToAddress([]byte(nid)),
BlsPublicKey: blsPubKey,
})
@ -58,15 +59,15 @@ func fakeGetInitShardState(numberOfShards, numOfNodes int) types.ShardState {
return shardState
}
func fakeNewNodeList(seed int64) []types.NodeID {
func fakeNewNodeList(seed int64) []shard.NodeID {
rand.Seed(seed)
numNewNodes := rand.Intn(10)
nodeList := []types.NodeID{}
nodeList := []shard.NodeID{}
for i := 0; i < numNewNodes; i++ {
nid := strconv.Itoa(int(rand.Int63()))
blsPubKey := [48]byte{}
copy(blsPubKey1[:], []byte(nid))
nodeList = append(nodeList, types.NodeID{
nodeList = append(nodeList, shard.NodeID{
EcdsaAddress: common.BytesToAddress([]byte(nid)),
BlsPublicKey: blsPubKey,
})
@ -80,7 +81,7 @@ func TestFakeNewNodeList(t *testing.T) {
}
func TestShuffle(t *testing.T) {
nodeList := []types.NodeID{
nodeList := []shard.NodeID{
{EcdsaAddress: common.Address{0x12}, BlsPublicKey: blsPubKey1},
{EcdsaAddress: common.Address{0x22}, BlsPublicKey: blsPubKey2},
{EcdsaAddress: common.Address{0x32}, BlsPublicKey: blsPubKey3},
@ -93,7 +94,7 @@ func TestShuffle(t *testing.T) {
{EcdsaAddress: common.Address{0x02}, BlsPublicKey: blsPubKey10},
}
cpList := []types.NodeID{}
cpList := []shard.NodeID{}
cpList = append(cpList, nodeList...)
Shuffle(nodeList)
cnt := 0
@ -120,7 +121,7 @@ func TestSortCommitteeBySize(t *testing.T) {
func TestUpdateShardState(t *testing.T) {
shardState := fakeGetInitShardState(6, 10)
ss := &ShardingState{epoch: 1, rnd: 42, shardState: shardState, numShards: len(shardState)}
newNodeList := []types.NodeID{
newNodeList := []shard.NodeID{
{EcdsaAddress: common.Address{0x12}, BlsPublicKey: blsPubKey1},
{EcdsaAddress: common.Address{0x22}, BlsPublicKey: blsPubKey2},
{EcdsaAddress: common.Address{0x32}, BlsPublicKey: blsPubKey3},
@ -136,7 +137,7 @@ func TestUpdateShardState(t *testing.T) {
func TestAssignNewNodes(t *testing.T) {
shardState := fakeGetInitShardState(2, 2)
ss := &ShardingState{epoch: 1, rnd: 42, shardState: shardState, numShards: len(shardState)}
newNodes := []types.NodeID{
newNodes := []shard.NodeID{
{EcdsaAddress: common.Address{0x12}, BlsPublicKey: blsPubKey1},
{EcdsaAddress: common.Address{0x22}, BlsPublicKey: blsPubKey2},
{EcdsaAddress: common.Address{0x32}, BlsPublicKey: blsPubKey3},

@ -34,6 +34,7 @@ import (
"golang.org/x/crypto/sha3"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
// Constants for block.
@ -135,8 +136,8 @@ func (h *Header) Logger(logger *zerolog.Logger) *zerolog.Logger {
}
// GetShardState returns the deserialized shard state object.
func (h *Header) GetShardState() (ShardState, error) {
shardState := ShardState{}
func (h *Header) GetShardState() (shard.ShardState, error) {
shardState := shard.ShardState{}
err := rlp.DecodeBytes(h.ShardState, &shardState)
if err != nil {
return nil, err
@ -546,7 +547,7 @@ func (b *Block) AddVdf(vdf []byte) {
}
// AddShardState add shardState into block header
func (b *Block) AddShardState(shardState ShardState) error {
func (b *Block) AddShardState(shardState shard.ShardState) error {
// Make a copy because ShardState.Hash() internally sorts entries.
// Store the sorted copy.
shardState = append(shardState[:0:0], shardState...)

@ -32,6 +32,7 @@ import (
"github.com/harmony-one/harmony/node/worker"
"github.com/harmony-one/harmony/p2p"
p2p_host "github.com/harmony-one/harmony/p2p/host"
"github.com/harmony-one/harmony/shard"
)
// State is a state of a node.
@ -201,7 +202,7 @@ type Node struct {
// Next shard state
nextShardState struct {
// The received master shard state
master *types.EpochShardState
master *shard.EpochShardState
// When for a leader to propose the next shard state,
// or for a validator to wait for a proposal before view change.

@ -9,17 +9,17 @@ import (
"github.com/ethereum/go-ethereum/common"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/harmony-one/harmony/common/denominations"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types"
common2 "github.com/harmony-one/harmony/internal/common"
nodeconfig "github.com/harmony-one/harmony/internal/configs/node"
"github.com/harmony-one/harmony/internal/genesis"
"github.com/harmony-one/harmony/internal/params"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
const (
@ -47,14 +47,14 @@ func (gi *genesisInitializer) InitChainDB(db ethdb.Database, shardID uint32) err
if c == nil {
return errors.New("cannot find local shard in genesis")
}
shardState = types.ShardState{*c}
shardState = shard.ShardState{*c}
}
gi.node.SetupGenesisBlock(db, shardID, shardState)
return nil
}
// SetupGenesisBlock sets up a genesis blockchain.
func (node *Node) SetupGenesisBlock(db ethdb.Database, shardID uint32, myShardState types.ShardState) {
func (node *Node) SetupGenesisBlock(db ethdb.Database, shardID uint32, myShardState shard.ShardState) {
utils.Logger().Info().Interface("shardID", shardID).Msg("setting up a brand new chain database")
if shardID == node.NodeConfig.ShardID {
node.isFirstTime = true

@ -33,6 +33,7 @@ import (
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/p2p"
"github.com/harmony-one/harmony/p2p/host"
"github.com/harmony-one/harmony/shard"
)
const (
@ -472,7 +473,7 @@ func (node *Node) validateNewShardState(block *types.Block, stakeInfo *map[commo
// We aren't expecting to reshard, so proceed to sign
return nil
}
shardState := &types.ShardState{}
shardState := &shard.ShardState{}
err := rlp.DecodeBytes(header.ShardState, shardState)
if err != nil {
return err
@ -491,7 +492,7 @@ func (node *Node) validateNewShardState(block *types.Block, stakeInfo *map[commo
return ctxerror.New("cannot calculate expected shard state").
WithCause(err)
}
if types.CompareShardState(expected, proposed) != 0 {
if shard.CompareShardState(expected, proposed) != 0 {
// TODO ek – log state proposal differences
// TODO ek – this error should trigger view change
err := errors.New("shard state proposal is different from expected")
@ -538,7 +539,7 @@ func (node *Node) validateNewShardState(block *types.Block, stakeInfo *map[commo
"leader proposed to continue against beacon decision")
}
// Did beaconchain say the same proposal?
if types.CompareCommittee(expected, &proposed) != 0 {
if shard.CompareCommittee(expected, &proposed) != 0 {
// TODO ek – log differences
// TODO ek – invoke view change
return errors.New("proposal differs from one in beacon chain")
@ -647,7 +648,7 @@ func (node *Node) broadcastEpochShardState(newBlock *types.Block) error {
return err
}
epochShardStateMessage := proto_node.ConstructEpochShardStateMessage(
types.EpochShardState{
shard.EpochShardState{
Epoch: newBlock.Header().Epoch.Uint64() + 1,
ShardState: shardState,
},
@ -679,13 +680,13 @@ func (node *Node) AddNewBlock(newBlock *types.Block) error {
type genesisNode struct {
ShardID uint32
MemberIndex int
NodeID types.NodeID
NodeID shard.NodeID
}
var (
genesisCatalogOnce sync.Once
genesisNodeByStakingAddress = make(map[common.Address]*genesisNode)
genesisNodeByConsensusKey = make(map[types.BlsPublicKey]*genesisNode)
genesisNodeByConsensusKey = make(map[shard.BlsPublicKey]*genesisNode)
)
func initGenesisCatalog() {
@ -708,7 +709,7 @@ func getGenesisNodeByStakingAddress(address common.Address) *genesisNode {
return genesisNodeByStakingAddress[address]
}
func getGenesisNodeByConsensusKey(key types.BlsPublicKey) *genesisNode {
func getGenesisNodeByConsensusKey(key shard.BlsPublicKey) *genesisNode {
genesisCatalogOnce.Do(initGenesisCatalog)
return genesisNodeByConsensusKey[key]
}
@ -884,7 +885,7 @@ func (node *Node) transitionIntoNextEpoch(shardState types.ShardState) {
*/
func findRoleInShardState(
key *bls.PublicKey, state types.ShardState,
key *bls.PublicKey, state shard.ShardState,
) (shardID uint32, isLeader bool) {
keyBytes := key.Serialize()
for idx, shard := range state {

@ -8,10 +8,12 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
"github.com/harmony-one/harmony/core"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/internal/ctxerror"
"github.com/harmony-one/harmony/internal/utils"
"github.com/harmony-one/harmony/shard"
)
// Constants of lower bound limit of a new block.
@ -193,7 +195,7 @@ func (node *Node) proposeLocalShardState(block *types.Block) {
return
}
masterShardState := node.nextShardState.master.ShardState
var localShardState types.ShardState
var localShardState shard.ShardState
committee := masterShardState.FindCommitteeByID(block.ShardID())
if committee != nil {
logger.Info().Msg("found local shard info; proposing it")

@ -4,13 +4,14 @@ import (
"encoding/hex"
"math/big"
"github.com/harmony-one/harmony/core/types"
"github.com/harmony-one/harmony/shard"
"github.com/harmony-one/harmony/contracts/structs"
"github.com/harmony-one/harmony/core"
"github.com/ethereum/go-ethereum/common"
"github.com/harmony-one/harmony/internal/utils"
"github.com/ethereum/go-ethereum/common/hexutil"
@ -45,7 +46,7 @@ func (node *Node) UpdateStakingList(stakeInfoReturnValue *structs.StakeInfoRetur
}
// True if the token is still staked within the locking period.
if curEpoch-startEpoch <= lockPeriodCount.Uint64()*lockPeriodInEpochs {
blsPubKey := types.BlsPublicKey{}
blsPubKey := shard.BlsPublicKey{}
copy(blsPubKey[:32], stakeInfoReturnValue.BlsPubicKeys1[i][:])
copy(blsPubKey[32:48], stakeInfoReturnValue.BlsPubicKeys2[i][:16])
node.CurrentStakes[addr] = &structs.StakeInfo{

@ -1,4 +1,4 @@
package types
package shard
import (
"bytes"

@ -1,4 +1,4 @@
package types
package shard
import (
"bytes"
Loading…
Cancel
Save