Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

R4R: random data seed #16

Merged
merged 1 commit into from
Jan 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 12 additions & 12 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,19 +48,19 @@ func (cfg *AdminConfig) Validate() {
}

type BBCConfig struct {
RpcAddr string `json:"rpc_addr"`
MnemonicType string `json:"mnemonic_type"`
AWSRegion string `json:"aws_region"`
AWSSecretName string `json:"aws_secret_name"`
Mnemonic string `json:"mnemonic"`
SleepMillisecondForWaitBlock int64 `json:"sleep_millisecond_for_wait_block"`
CleanUpBlockInterval uint64 `json:"clean_up_block_interval"`
BlockIntervalForCleanUpUndeliveredPackages uint64 `json:"block_interval_for_clean_up_undelivered_packages"`
BehindBlockThreshold uint64 `json:"behind_block_threshold"`
RpcAddrs []string `json:"rpc_addrs"`
MnemonicType string `json:"mnemonic_type"`
AWSRegion string `json:"aws_region"`
AWSSecretName string `json:"aws_secret_name"`
Mnemonic string `json:"mnemonic"`
SleepMillisecondForWaitBlock int64 `json:"sleep_millisecond_for_wait_block"`
CleanUpBlockInterval uint64 `json:"clean_up_block_interval"`
BlockIntervalForCleanUpUndeliveredPackages uint64 `json:"block_interval_for_clean_up_undelivered_packages"`
BehindBlockThreshold uint64 `json:"behind_block_threshold"`
}

func (cfg *BBCConfig) Validate() {
if cfg.RpcAddr == "" {
if len(cfg.RpcAddrs) == 0 {
panic("rpc endpoint of Binance chain should not be empty")
}
if cfg.MnemonicType == "" {
Expand Down Expand Up @@ -88,14 +88,14 @@ type BSCConfig struct {
AWSRegion string `json:"aws_region"`
AWSSecretName string `json:"aws_secret_name"`
PrivateKey string `json:"private_key"`
Provider string `json:"provider"`
Providers []string `json:"providers"`
GasLimit uint64 `json:"gas_limit"`
GasPrice uint64 `json:"gas_price"`
MonitorDataSeedList []string `json:"monitor_data_seed_list"`
}

func (cfg *BSCConfig) Validate() {
if cfg.Provider == "" {
if len(cfg.Providers) == 0 {
panic(fmt.Sprintf("provider address of Binance Smart Chain should not be empty"))
}

Expand Down
8 changes: 6 additions & 2 deletions config/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
"competition_mode": true
},
"bbc_config": {
"rpc_addr": "http://data-seed-prealpha-1-s1.binance.org:80",
"rpc_addrs": [
"http://data-seed-prealpha-1-s1.binance.org:80"
],
"mnemonic_type": "local_mnemonic",
"aws_region": "",
"aws_secret_name": "",
Expand All @@ -21,7 +23,9 @@
"aws_region": "",
"aws_secret_name": "",
"private_key": "",
"provider": "https://data-seed-prebsc-1-s1.binance.org:8545",
"providers": [
"https://data-seed-prebsc-1-s1.binance.org:8545"
],
"gas_limit": 4700000,
"gas_price": 20000000000,
"monitor_data_seed_list": []
Expand Down
69 changes: 41 additions & 28 deletions executor/bbc_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import (
"encoding/json"
"fmt"
"math"
"math/rand"
"strconv"
"strings"
"time"

"github.com/binance-chain/bsc-double-sign-sdk/client"
"github.com/binance-chain/bsc-double-sign-sdk/types/bsc"
Expand All @@ -23,7 +25,7 @@ import (
)

type BBCExecutor struct {
RpcClient *rpc.HTTP
RpcClients []*rpc.HTTP
Config *config.Config
keyManager keys.KeyManager
sourceChainID common.CrossChainID
Expand Down Expand Up @@ -55,43 +57,54 @@ func getMnemonic(cfg *config.BBCConfig) (string, error) {
return mnemonic, nil
}

func NewBBCExecutor(cfg *config.Config, networkType ctypes.ChainNetwork) (*BBCExecutor, error) {
rpcClient := rpc.NewRPCClient(cfg.BBCConfig.RpcAddr, networkType)
func initBBCClients(keyManager keys.KeyManager, providers []string, network ctypes.ChainNetwork) []*rpc.HTTP {
bcClients := make([]*rpc.HTTP, 0)
for _, provider := range providers {
rpcClient := rpc.NewRPCClient(provider, network)
rpcClient.SetKeyManager(keyManager)
bcClients = append(bcClients, rpcClient)
}
return bcClients
}

var keyManager keys.KeyManager
if len(cfg.BSCConfig.MonitorDataSeedList) >= 2 {
mnemonic, err := getMnemonic(&cfg.BBCConfig)
if err != nil {
return nil, err
}
func NewBBCExecutor(cfg *config.Config, networkType ctypes.ChainNetwork) (*BBCExecutor, error) {
mnemonic, err := getMnemonic(&cfg.BBCConfig)
if err != nil {
panic(err.Error())
}

keyManager, err = keys.NewMnemonicKeyManager(mnemonic)
if err != nil {
return nil, err
}
rpcClient.SetKeyManager(keyManager)
keyManager, err := keys.NewMnemonicKeyManager(mnemonic)
if err != nil {
panic(err.Error())
}

return &BBCExecutor{
RpcClient: rpcClient,
RpcClients: initBBCClients(keyManager, cfg.BBCConfig.RpcAddrs, networkType),
keyManager: keyManager,
Config: cfg,
sourceChainID: common.CrossChainID(cfg.CrossChainConfig.SourceChainID),
destChainID: common.CrossChainID(cfg.CrossChainConfig.DestChainID),
}, nil
}

func (executor *BBCExecutor) GetClient() *rpc.HTTP {
r := rand.New(rand.NewSource(time.Now().UnixNano()))

idx := r.Intn(len(executor.RpcClients))
return executor.RpcClients[idx]
}

func (executor *BBCExecutor) SubmitEvidence(headers []*bsc.Header) (*coretypes.ResultBroadcastTx, error) {
return client.BSCSubmitEvidence(executor.RpcClient, executor.keyManager.GetAddr(), headers, rpc.Sync)
return client.BSCSubmitEvidence(executor.GetClient(), executor.keyManager.GetAddr(), headers, rpc.Sync)
}

func (executor *BBCExecutor) MonitorCrossChainPackage(height int64, preValidatorsHash cmn.HexBytes) (*common.TaskSet, cmn.HexBytes, error) {
block, err := executor.RpcClient.Block(&height)
block, err := executor.GetClient().Block(&height)
if err != nil {
return nil, nil, err
}

blockResults, err := executor.RpcClient.BlockResults(&height)
blockResults, err := executor.GetClient().BlockResults(&height)
if err != nil {
return nil, nil, err
}
Expand Down Expand Up @@ -161,9 +174,9 @@ func (executor *BBCExecutor) MonitorCrossChainPackage(height int64, preValidator
func (executor *BBCExecutor) MonitorValidatorSetChange(height int64, preValidatorsHash cmn.HexBytes) (bool, cmn.HexBytes, error) {
validatorSetChanged := false

block, err := executor.RpcClient.Block(&height)
block, err := executor.GetClient().Block(&height)
if err != nil {
return validatorSetChanged, nil, err
return false, nil, err
}

var curValidatorsHash cmn.HexBytes
Expand All @@ -181,18 +194,18 @@ func (executor *BBCExecutor) MonitorValidatorSetChange(height int64, preValidato
}

func (executor *BBCExecutor) GetInitConsensusState(height int64) (*common.ConsensusState, error) {
status, err := executor.RpcClient.Status()
status, err := executor.GetClient().Status()
if err != nil {
return nil, err
}

nextValHeight := height + 1
nextValidatorSet, err := executor.RpcClient.Validators(&nextValHeight)
nextValidatorSet, err := executor.GetClient().Validators(&nextValHeight)
if err != nil {
return nil, err
}

header, err := executor.RpcClient.Block(&height)
header, err := executor.GetClient().Block(&height)
if err != nil {
return nil, err
}
Expand All @@ -215,17 +228,17 @@ func (executor *BBCExecutor) GetInitConsensusState(height int64) (*common.Consen
func (executor *BBCExecutor) QueryTendermintHeader(height int64) (*common.Header, error) {
nextHeight := height + 1

commit, err := executor.RpcClient.Commit(&height)
commit, err := executor.GetClient().Commit(&height)
if err != nil {
return nil, err
}

validators, err := executor.RpcClient.Validators(&height)
validators, err := executor.GetClient().Validators(&height)
if err != nil {
return nil, err
}

nextvalidators, err := executor.RpcClient.Validators(&nextHeight)
nextvalidators, err := executor.GetClient().Validators(&nextHeight)
if err != nil {
return nil, err
}
Expand All @@ -246,7 +259,7 @@ func (executor *BBCExecutor) QueryKeyWithProof(key []byte, height int64) (int64,
}

path := fmt.Sprintf("/store/%s/%s", packageStoreName, "key")
result, err := executor.RpcClient.ABCIQueryWithOptions(path, key, opts)
result, err := executor.GetClient().ABCIQueryWithOptions(path, key, opts)
if err != nil {
return 0, nil, nil, nil, err
}
Expand All @@ -267,7 +280,7 @@ func (executor *BBCExecutor) GetNextSequence(channelID common.CrossChainChannelI
path := fmt.Sprintf("/store/%s/%s", sequenceStoreName, "key")
key := buildChannelSequenceKey(executor.destChainID, channelID)

response, err := executor.RpcClient.ABCIQueryWithOptions(path, key, opts)
response, err := executor.GetClient().ABCIQueryWithOptions(path, key, opts)
if err != nil {
return 0, err
}
Expand Down
50 changes: 34 additions & 16 deletions executor/bsc_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"math/big"
"math/rand"
"time"

"github.com/ethereum/go-ethereum/accounts/abi/bind"
Expand All @@ -27,7 +28,7 @@ import (
type BSCExecutor struct {
db *gorm.DB
bbcExecutor *BBCExecutor
bscClient *ethclient.Client
bscClients []*ethclient.Client
sourceChainID relayercommon.CrossChainID
destChainID relayercommon.CrossChainID
privateKey *ecdsa.PrivateKey
Expand Down Expand Up @@ -62,11 +63,21 @@ func getPrivateKey(cfg *config.BSCConfig) (*ecdsa.PrivateKey, error) {
return privKey, nil
}

func NewBSCExecutor(db *gorm.DB, bbcExecutor *BBCExecutor, cfg *config.Config) (*BSCExecutor, error) {
bscClient, err := ethclient.Dial(cfg.BSCConfig.Provider)
if err != nil {
return nil, err
func initClients(providers []string) []*ethclient.Client {
clients := make([]*ethclient.Client, 0)

for _, provider := range providers {
client, err := ethclient.Dial(provider)
if err != nil {
panic("new eth client error")
}
clients = append(clients, client)
}

return clients
}

func NewBSCExecutor(db *gorm.DB, bbcExecutor *BBCExecutor, cfg *config.Config) (*BSCExecutor, error) {
privKey, err := getPrivateKey(&cfg.BSCConfig)
if err != nil {
return nil, err
Expand All @@ -81,7 +92,7 @@ func NewBSCExecutor(db *gorm.DB, bbcExecutor *BBCExecutor, cfg *config.Config) (
return &BSCExecutor{
db: db,
bbcExecutor: bbcExecutor,
bscClient: bscClient,
bscClients: initClients(cfg.BSCConfig.Providers),
privateKey: privKey,
txSender: txSender,
sourceChainID: relayercommon.CrossChainID(cfg.CrossChainConfig.SourceChainID),
Expand All @@ -90,8 +101,15 @@ func NewBSCExecutor(db *gorm.DB, bbcExecutor *BBCExecutor, cfg *config.Config) (
}, nil
}

func (executor *BSCExecutor) GetClient() *ethclient.Client {
r := rand.New(rand.NewSource(time.Now().UnixNano()))

idx := r.Intn(len(executor.bscClients))
return executor.bscClients[idx]
}

func (executor *BSCExecutor) getTransactor() (*bind.TransactOpts, error) {
nonce, err := executor.bscClient.PendingNonceAt(context.Background(), executor.txSender)
nonce, err := executor.GetClient().PendingNonceAt(context.Background(), executor.txSender)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -122,7 +140,7 @@ func (executor *BSCExecutor) SyncTendermintLightClientHeader(height uint64) (com
return common.Hash{}, err
}

instance, err := tendermintlightclient.NewTendermintlightclient(tendermintLightClientContractAddr, executor.bscClient)
instance, err := tendermintlightclient.NewTendermintlightclient(tendermintLightClientContractAddr, executor.GetClient())
if err != nil {
return common.Hash{}, err
}
Expand Down Expand Up @@ -181,7 +199,7 @@ func (executor *BSCExecutor) CallBuildInSystemContract(channelID relayercommon.C
return common.Hash{}, err
}

crossChainInstance, err := crosschain.NewCrosschain(crossChainContractAddr, executor.bscClient)
crossChainInstance, err := crosschain.NewCrosschain(crossChainContractAddr, executor.GetClient())
if err != nil {
return common.Hash{}, err
}
Expand Down Expand Up @@ -280,7 +298,7 @@ func (executor *BSCExecutor) BatchRelayCrossChainPackages(channelID relayercommo
}

func (executor *BSCExecutor) IsRelayer() (bool, error) {
instance, err := relayerhub.NewRelayerhub(relayerHubContractAddr, executor.bscClient)
instance, err := relayerhub.NewRelayerhub(relayerHubContractAddr, executor.GetClient())
if err != nil {
return false, err
}
Expand All @@ -303,7 +321,7 @@ func (executor *BSCExecutor) RegisterRelayer() (common.Hash, error) {
return common.Hash{}, err
}

instance, err := relayerhub.NewRelayerhub(relayerHubContractAddr, executor.bscClient)
instance, err := relayerhub.NewRelayerhub(relayerHubContractAddr, executor.GetClient())
if err != nil {
return common.Hash{}, err
}
Expand All @@ -322,7 +340,7 @@ func (executor *BSCExecutor) QueryReward() (*big.Int, error) {
return nil, err
}

instance, err := relayerincentivize.NewRelayerincentivize(relayerIncentivizeContractAddr, executor.bscClient)
instance, err := relayerincentivize.NewRelayerincentivize(relayerIncentivizeContractAddr, executor.GetClient())
if err != nil {
return nil, err
}
Expand All @@ -340,7 +358,7 @@ func (executor *BSCExecutor) ClaimReward() (common.Hash, error) {
return common.Hash{}, err
}

instance, err := relayerincentivize.NewRelayerincentivize(relayerIncentivizeContractAddr, executor.bscClient)
instance, err := relayerincentivize.NewRelayerincentivize(relayerIncentivizeContractAddr, executor.GetClient())
if err != nil {
return common.Hash{}, err
}
Expand All @@ -353,7 +371,7 @@ func (executor *BSCExecutor) ClaimReward() (common.Hash, error) {
}

func (executor *BSCExecutor) GetNextSequence(channelID relayercommon.CrossChainChannelID) (uint64, error) {
crossChainInstance, err := crosschain.NewCrosschain(crossChainContractAddr, executor.bscClient)
crossChainInstance, err := crosschain.NewCrosschain(crossChainContractAddr, executor.GetClient())
if err != nil {
return 0, err
}
Expand All @@ -367,11 +385,11 @@ func (executor *BSCExecutor) GetNextSequence(channelID relayercommon.CrossChainC
}

func (executor *BSCExecutor) GetTxRecipient(txHash common.Hash) (*types.Receipt, error) {
return executor.bscClient.TransactionReceipt(context.Background(), txHash)
return executor.GetClient().TransactionReceipt(context.Background(), txHash)
}

func (executor *BSCExecutor) GetRelayerBalance() (*big.Int, error) {
return executor.bscClient.BalanceAt(context.Background(), executor.txSender, nil)
return executor.GetClient().BalanceAt(context.Background(), executor.txSender, nil)
}

func (executor *BSCExecutor) saveRelayTx(relayTxModel *model.RelayTransaction) error {
Expand Down