You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
329 lines
9.6 KiB
329 lines
9.6 KiB
6 years ago
|
package syncing
|
||
6 years ago
|
|
||
|
import (
|
||
6 years ago
|
"bytes"
|
||
6 years ago
|
"reflect"
|
||
6 years ago
|
"sort"
|
||
6 years ago
|
"sync"
|
||
|
"time"
|
||
|
|
||
|
"github.com/Workiva/go-datastructures/queue"
|
||
6 years ago
|
"github.com/harmony-one/harmony/blockchain"
|
||
6 years ago
|
"github.com/harmony-one/harmony/log"
|
||
6 years ago
|
"github.com/harmony-one/harmony/p2p"
|
||
6 years ago
|
"github.com/harmony-one/harmony/services/syncing/downloader"
|
||
6 years ago
|
)
|
||
|
|
||
6 years ago
|
// Constants for syncing.
|
||
|
const (
|
||
6 years ago
|
ConsensusRatio = float64(0.66)
|
||
|
SleepTimeAfterNonConsensusBlockHashes = time.Second * 30
|
||
|
TimesToFail = 5
|
||
6 years ago
|
)
|
||
|
|
||
6 years ago
|
// SyncPeerConfig is peer config to sync.
|
||
6 years ago
|
type SyncPeerConfig struct {
|
||
6 years ago
|
ip string
|
||
|
port string
|
||
|
client *downloader.Client
|
||
|
blockHashes [][]byte
|
||
6 years ago
|
}
|
||
|
|
||
6 years ago
|
// Log is the temporary log for syncing.
|
||
6 years ago
|
var Log = log.New()
|
||
|
|
||
6 years ago
|
// SyncBlockTask is the task struct to sync a specific block.
|
||
6 years ago
|
type SyncBlockTask struct {
|
||
|
index int
|
||
6 years ago
|
blockHash []byte
|
||
6 years ago
|
}
|
||
6 years ago
|
|
||
|
// SyncConfig contains an array of SyncPeerConfig.
|
||
6 years ago
|
type SyncConfig struct {
|
||
6 years ago
|
peers []*SyncPeerConfig
|
||
6 years ago
|
}
|
||
|
|
||
6 years ago
|
// GetStateSync returns the implementation of StateSyncInterface interface.
|
||
|
func GetStateSync() *StateSync {
|
||
|
return &StateSync{}
|
||
|
}
|
||
|
|
||
|
// StateSync is the struct that implements StateSyncInterface.
|
||
6 years ago
|
type StateSync struct {
|
||
6 years ago
|
peerNumber int
|
||
|
activePeerNumber int
|
||
|
blockHeight int
|
||
|
syncConfig *SyncConfig
|
||
|
stateSyncTaskQueue *queue.Queue
|
||
6 years ago
|
}
|
||
|
|
||
6 years ago
|
// CreateTestSyncPeerConfig used for testing.
|
||
|
func CreateTestSyncPeerConfig(client *downloader.Client, blockHashes [][]byte) *SyncPeerConfig {
|
||
|
return &SyncPeerConfig{
|
||
|
client: client,
|
||
|
blockHashes: blockHashes,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// CompareSyncPeerConfigByblockHashes compares two SyncPeerConfig by blockHashes.
|
||
|
func CompareSyncPeerConfigByblockHashes(a *SyncPeerConfig, b *SyncPeerConfig) int {
|
||
6 years ago
|
if len(a.blockHashes) != len(b.blockHashes) {
|
||
|
if len(a.blockHashes) < len(b.blockHashes) {
|
||
|
return -1
|
||
|
}
|
||
|
return 1
|
||
|
}
|
||
|
for id := range a.blockHashes {
|
||
|
if !reflect.DeepEqual(a.blockHashes[id], b.blockHashes[id]) {
|
||
|
return bytes.Compare(a.blockHashes[id], b.blockHashes[id])
|
||
|
}
|
||
|
}
|
||
|
return 0
|
||
|
}
|
||
|
|
||
6 years ago
|
// GetBlockHashes gets block hashes by calling grpc request to the corresponding peer.
|
||
6 years ago
|
func (peerConfig *SyncPeerConfig) GetBlockHashes() error {
|
||
|
if peerConfig.client == nil {
|
||
|
return ErrSyncPeerConfigClientNotReady
|
||
|
}
|
||
|
response := peerConfig.client.GetBlockHashes()
|
||
|
peerConfig.blockHashes = make([][]byte, len(response.Payload))
|
||
|
for i := range response.Payload {
|
||
|
peerConfig.blockHashes[i] = make([]byte, len(response.Payload[i]))
|
||
|
copy(peerConfig.blockHashes[i], response.Payload[i])
|
||
|
}
|
||
|
return nil
|
||
|
}
|
||
|
|
||
6 years ago
|
// GetBlocks gets blocks by calling grpc request to the corresponding peer.
|
||
6 years ago
|
func (peerConfig *SyncPeerConfig) GetBlocks(hashes [][]byte) ([][]byte, error) {
|
||
6 years ago
|
if peerConfig.client == nil {
|
||
|
return nil, ErrSyncPeerConfigClientNotReady
|
||
|
}
|
||
6 years ago
|
response := peerConfig.client.GetBlocks(hashes)
|
||
6 years ago
|
return response.Payload, nil
|
||
|
}
|
||
|
|
||
6 years ago
|
// ProcessStateSyncFromPeers used to do state sync.
|
||
|
func (ss *StateSync) ProcessStateSyncFromPeers(peers []p2p.Peer, bc *blockchain.Blockchain) (chan struct{}, error) {
|
||
|
// TODO: Validate peers.
|
||
6 years ago
|
done := make(chan struct{})
|
||
|
go func() {
|
||
|
ss.StartStateSync(peers, bc)
|
||
|
done <- struct{}{}
|
||
|
}()
|
||
|
return done, nil
|
||
|
}
|
||
|
|
||
6 years ago
|
// CreateSyncConfig creates SyncConfig for StateSync object.
|
||
6 years ago
|
func (ss *StateSync) CreateSyncConfig(peers []p2p.Peer) {
|
||
6 years ago
|
Log.Debug("CreateSyncConfig: len of peers", "len", len(peers))
|
||
|
Log.Debug("CreateSyncConfig: len of peers", "peers", peers)
|
||
6 years ago
|
ss.peerNumber = len(peers)
|
||
6 years ago
|
Log.Debug("CreateSyncConfig: hello")
|
||
6 years ago
|
ss.syncConfig = &SyncConfig{
|
||
6 years ago
|
peers: make([]*SyncPeerConfig, ss.peerNumber),
|
||
6 years ago
|
}
|
||
6 years ago
|
for id := range ss.syncConfig.peers {
|
||
6 years ago
|
ss.syncConfig.peers[id] = &SyncPeerConfig{
|
||
6 years ago
|
ip: peers[id].IP,
|
||
6 years ago
|
port: peers[id].Port,
|
||
|
}
|
||
6 years ago
|
Log.Debug("CreateSyncConfig: peer port to connect", "port", peers[id].Port)
|
||
6 years ago
|
}
|
||
6 years ago
|
Log.Info("syncing: Finished creating SyncConfig.")
|
||
6 years ago
|
}
|
||
6 years ago
|
|
||
6 years ago
|
// MakeConnectionToPeers makes grpc connection to all peers.
|
||
|
func (ss *StateSync) MakeConnectionToPeers() {
|
||
6 years ago
|
var wg sync.WaitGroup
|
||
6 years ago
|
wg.Add(ss.peerNumber)
|
||
6 years ago
|
|
||
6 years ago
|
for id := range ss.syncConfig.peers {
|
||
6 years ago
|
go func(peerConfig *SyncPeerConfig) {
|
||
|
defer wg.Done()
|
||
6 years ago
|
peerConfig.client = downloader.ClientSetup(peerConfig.ip, peerConfig.port)
|
||
6 years ago
|
}(ss.syncConfig.peers[id])
|
||
6 years ago
|
}
|
||
|
wg.Wait()
|
||
6 years ago
|
ss.CleanUpNilPeers()
|
||
6 years ago
|
Log.Info("syncing: Finished making connection to peers.")
|
||
6 years ago
|
}
|
||
|
|
||
|
// CleanUpNilPeers cleans up peer with nil client and recalculate activePeerNumber.
|
||
|
func (ss *StateSync) CleanUpNilPeers() {
|
||
6 years ago
|
ss.activePeerNumber = 0
|
||
|
for _, configPeer := range ss.syncConfig.peers {
|
||
6 years ago
|
if configPeer.client != nil {
|
||
6 years ago
|
ss.activePeerNumber++
|
||
6 years ago
|
}
|
||
|
}
|
||
6 years ago
|
}
|
||
|
|
||
6 years ago
|
// GetHowManyMaxConsensus returns max number of consensus nodes and the first ID of consensus group.
|
||
|
// Assumption: all peers are sorted by CompareSyncPeerConfigByBlockHashes first.
|
||
|
func (syncConfig *SyncConfig) GetHowManyMaxConsensus() (int, int) {
|
||
6 years ago
|
// As all peers are sorted by their blockHashes, all equal blockHashes should come together and consecutively.
|
||
|
curCount := 0
|
||
|
curFirstID := -1
|
||
|
maxCount := 0
|
||
|
maxFirstID := -1
|
||
|
for i := range syncConfig.peers {
|
||
6 years ago
|
if curFirstID == -1 || CompareSyncPeerConfigByblockHashes(syncConfig.peers[curFirstID], syncConfig.peers[i]) != 0 {
|
||
6 years ago
|
curCount = 1
|
||
|
curFirstID = i
|
||
|
} else {
|
||
|
curCount++
|
||
6 years ago
|
}
|
||
6 years ago
|
if curCount > maxCount {
|
||
|
maxCount = curCount
|
||
|
maxFirstID = curFirstID
|
||
|
}
|
||
|
}
|
||
|
return maxFirstID, maxCount
|
||
|
}
|
||
|
|
||
6 years ago
|
// InitForTesting used for testing.
|
||
|
func (syncConfig *SyncConfig) InitForTesting(client *downloader.Client, blockHashes [][]byte) {
|
||
|
for i := range syncConfig.peers {
|
||
|
syncConfig.peers[i].blockHashes = blockHashes
|
||
|
syncConfig.peers[i].client = client
|
||
|
}
|
||
|
}
|
||
|
|
||
6 years ago
|
// CleanUpPeers cleans up all peers whose blockHashes are not equal to consensus block hashes.
|
||
|
func (syncConfig *SyncConfig) CleanUpPeers(maxFirstID int) {
|
||
6 years ago
|
fixedPeer := syncConfig.peers[maxFirstID]
|
||
|
for i := 0; i < len(syncConfig.peers); i++ {
|
||
|
if CompareSyncPeerConfigByblockHashes(fixedPeer, syncConfig.peers[i]) != 0 {
|
||
6 years ago
|
// TODO: move it into a util delete func.
|
||
|
// See tip https://github.com/golang/go/wiki/SliceTricks
|
||
|
// Close the client and remove the peer out of the
|
||
|
syncConfig.peers[i].client.Close()
|
||
|
copy(syncConfig.peers[i:], syncConfig.peers[i+1:])
|
||
|
syncConfig.peers[len(syncConfig.peers)-1] = nil
|
||
|
syncConfig.peers = syncConfig.peers[:len(syncConfig.peers)-1]
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
6 years ago
|
// GetBlockHashesConsensusAndCleanUp chesk if all consensus hashes are equal.
|
||
|
func (ss *StateSync) GetBlockHashesConsensusAndCleanUp() bool {
|
||
6 years ago
|
// Sort all peers by the blockHashes.
|
||
|
sort.Slice(ss.syncConfig.peers, func(i, j int) bool {
|
||
|
return CompareSyncPeerConfigByblockHashes(ss.syncConfig.peers[i], ss.syncConfig.peers[j]) == -1
|
||
|
})
|
||
6 years ago
|
maxFirstID, maxCount := ss.syncConfig.GetHowManyMaxConsensus()
|
||
6 years ago
|
if float64(maxCount) >= ConsensusRatio*float64(ss.activePeerNumber) {
|
||
|
ss.syncConfig.CleanUpPeers(maxFirstID)
|
||
|
ss.CleanUpNilPeers()
|
||
|
return true
|
||
6 years ago
|
}
|
||
6 years ago
|
return false
|
||
6 years ago
|
}
|
||
6 years ago
|
|
||
6 years ago
|
// GetConsensusHashes gets all hashes needed to download.
|
||
6 years ago
|
func (ss *StateSync) GetConsensusHashes() bool {
|
||
|
count := 0
|
||
6 years ago
|
for {
|
||
|
var wg sync.WaitGroup
|
||
6 years ago
|
wg.Add(ss.activePeerNumber)
|
||
6 years ago
|
|
||
6 years ago
|
for id := range ss.syncConfig.peers {
|
||
|
if ss.syncConfig.peers[id].client == nil {
|
||
6 years ago
|
continue
|
||
|
}
|
||
|
go func(peerConfig *SyncPeerConfig) {
|
||
|
defer wg.Done()
|
||
6 years ago
|
response := peerConfig.client.GetBlockHashes()
|
||
|
peerConfig.blockHashes = response.Payload
|
||
6 years ago
|
}(ss.syncConfig.peers[id])
|
||
6 years ago
|
}
|
||
6 years ago
|
wg.Wait()
|
||
6 years ago
|
if ss.GetBlockHashesConsensusAndCleanUp() {
|
||
6 years ago
|
break
|
||
6 years ago
|
}
|
||
6 years ago
|
if count > TimesToFail {
|
||
|
Log.Info("GetConsensusHashes: reached # of times to failed")
|
||
|
return false
|
||
|
}
|
||
|
count++
|
||
|
time.Sleep(SleepTimeAfterNonConsensusBlockHashes)
|
||
6 years ago
|
}
|
||
6 years ago
|
Log.Info("syncing: Finished getting consensus block hashes.")
|
||
|
return true
|
||
6 years ago
|
}
|
||
6 years ago
|
|
||
6 years ago
|
// getConsensusHashes gets all hashes needed to download.
|
||
6 years ago
|
func (ss *StateSync) generateStateSyncTaskQueue(bc *blockchain.Blockchain) {
|
||
6 years ago
|
ss.stateSyncTaskQueue = queue.New(0)
|
||
6 years ago
|
for _, configPeer := range ss.syncConfig.peers {
|
||
6 years ago
|
if configPeer.client != nil {
|
||
6 years ago
|
|
||
|
ss.blockHeight = len(configPeer.blockHashes)
|
||
|
bc.Blocks = append(bc.Blocks, make([]*blockchain.Block, ss.blockHeight-len(bc.Blocks))...)
|
||
6 years ago
|
for id, blockHash := range configPeer.blockHashes {
|
||
6 years ago
|
if bc.Blocks[id] == nil || !reflect.DeepEqual(bc.Blocks[id].Hash[:], blockHash) {
|
||
|
ss.stateSyncTaskQueue.Put(SyncBlockTask{index: id, blockHash: blockHash})
|
||
6 years ago
|
// TODO(minhdoan): Check error
|
||
6 years ago
|
}
|
||
6 years ago
|
}
|
||
6 years ago
|
break
|
||
6 years ago
|
}
|
||
|
}
|
||
6 years ago
|
Log.Info("syncing: Finished generateStateSyncTaskQueue.")
|
||
6 years ago
|
}
|
||
|
|
||
|
// downloadBlocks downloads blocks from state sync task queue.
|
||
|
func (ss *StateSync) downloadBlocks(bc *blockchain.Blockchain) {
|
||
6 years ago
|
// Initialize blockchain
|
||
6 years ago
|
var wg sync.WaitGroup
|
||
6 years ago
|
wg.Add(ss.activePeerNumber)
|
||
|
for i := range ss.syncConfig.peers {
|
||
|
if ss.syncConfig.peers[i].client == nil {
|
||
6 years ago
|
continue
|
||
6 years ago
|
}
|
||
6 years ago
|
go func(peerConfig *SyncPeerConfig, stateSyncTaskQueue *queue.Queue, bc *blockchain.Blockchain) {
|
||
6 years ago
|
defer wg.Done()
|
||
6 years ago
|
for !stateSyncTaskQueue.Empty() {
|
||
|
task, err := stateSyncTaskQueue.Poll(1, time.Millisecond)
|
||
6 years ago
|
if err == queue.ErrTimeout {
|
||
|
break
|
||
|
}
|
||
|
syncTask := task[0].(SyncBlockTask)
|
||
6 years ago
|
for {
|
||
|
id := syncTask.index
|
||
6 years ago
|
payload, err := peerConfig.GetBlocks([][]byte{syncTask.blockHash})
|
||
6 years ago
|
if err == nil {
|
||
6 years ago
|
// As of now, only send and ask for one block.
|
||
|
bc.Blocks[id], err = blockchain.DeserializeBlock(payload[0])
|
||
|
if err == nil {
|
||
6 years ago
|
break
|
||
|
}
|
||
6 years ago
|
}
|
||
6 years ago
|
}
|
||
|
}
|
||
6 years ago
|
}(ss.syncConfig.peers[i], ss.stateSyncTaskQueue, bc)
|
||
6 years ago
|
}
|
||
6 years ago
|
wg.Wait()
|
||
6 years ago
|
Log.Info("syncing: Finished downloadBlocks.")
|
||
6 years ago
|
}
|
||
|
|
||
6 years ago
|
// StartStateSync starts state sync.
|
||
6 years ago
|
func (ss *StateSync) StartStateSync(peers []p2p.Peer, bc *blockchain.Blockchain) bool {
|
||
6 years ago
|
// Creates sync config.
|
||
6 years ago
|
ss.CreateSyncConfig(peers)
|
||
6 years ago
|
// Makes connections to peers.
|
||
6 years ago
|
ss.MakeConnectionToPeers()
|
||
6 years ago
|
// Gets consensus hashes.
|
||
|
if !ss.GetConsensusHashes() {
|
||
|
return false
|
||
|
}
|
||
|
ss.generateStateSyncTaskQueue(bc)
|
||
|
// Download blocks.
|
||
|
if ss.stateSyncTaskQueue.Len() > 0 {
|
||
|
ss.downloadBlocks(bc)
|
||
6 years ago
|
}
|
||
6 years ago
|
return true
|
||
6 years ago
|
}
|