Skip to content

Commit

Permalink
Merge pull request #98 from bnb-chain/opbnb
Browse files Browse the repository at this point in the history
feat: support OPBNB cross-chain
  • Loading branch information
alexgao001 authored Nov 14, 2023
2 parents 5c249c5 + 643d883 commit ee9f492
Show file tree
Hide file tree
Showing 14 changed files with 206 additions and 86 deletions.
7 changes: 6 additions & 1 deletion assembler/bsc_assembler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/hex"
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
oracletypes "github.com/cosmos/cosmos-sdk/x/oracle/types"
"time"

"github.com/bnb-chain/greenfield-relayer/common"
Expand Down Expand Up @@ -59,7 +60,11 @@ func (a *BSCAssembler) assemblePackagesAndClaimForOracleChannel(channelId types.
}

func (a *BSCAssembler) process(channelId types.ChannelId) error {
inturnRelayer, err := a.greenfieldExecutor.GetInturnRelayer()
claimSrcChain := oracletypes.CLAIM_SRC_CHAIN_BSC
if a.config.BSCConfig.IsOpCrossChain() {
claimSrcChain = oracletypes.CLAIM_SRC_CHAIN_OP_BNB
}
inturnRelayer, err := a.greenfieldExecutor.GetInturnRelayer(claimSrcChain)
if err != nil {
return fmt.Errorf("failed to get inturn relayer, err=%s", err.Error())
}
Expand Down
9 changes: 7 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ func (cfg *GreenfieldConfig) Validate() {
}

type BSCConfig struct {
OpBNB bool `json:"op_bnb"`
KeyType string `json:"key_type"`
AWSRegion string `json:"aws_region"`
AWSSecretName string `json:"aws_secret_name"`
Expand Down Expand Up @@ -105,11 +106,15 @@ func (cfg *BSCConfig) Validate() {
if cfg.GasLimit == 0 {
panic("gas_limit of BNB Smart Chain should be larger than 0")
}
if cfg.NumberOfBlocksForFinality < 2 || cfg.NumberOfBlocksForFinality > 21 {
panic("NumberOfBlocksForFinality should be [2, 21]")
if cfg.NumberOfBlocksForFinality < 1 || cfg.NumberOfBlocksForFinality > 21 {
panic("NumberOfBlocksForFinality should be [1, 21]")
}
}

func (cfg *BSCConfig) IsOpCrossChain() bool {
return cfg.OpBNB
}

type RelayConfig struct {
BSCToGreenfieldInturnRelayerTimeout int64 `json:"bsc_to_greenfield_inturn_relayer_timeout"` // in second
GreenfieldToBSCInturnRelayerTimeout int64 `json:"greenfield_to_bsc_inturn_relayer_timeout"` // in second
Expand Down
1 change: 1 addition & 0 deletions config/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"use_websocket": true
},
"bsc_config": {
"op_bnb": false,
"key_type": "local_private_key",
"aws_region": "",
"aws_secret_name": "",
Expand Down
7 changes: 6 additions & 1 deletion db/dao/bsc_dao.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package dao

import (
"database/sql"
"github.com/cometbft/cometbft/votepool"
"time"

"gorm.io/gorm"
Expand Down Expand Up @@ -142,7 +143,7 @@ func (d *BSCDao) SaveBatchPackages(pkgs []*model.BscRelayPackage) error {
})
}

func (d *BSCDao) DeleteBlockAndPackagesAtHeight(height uint64) error {
func (d *BSCDao) DeleteBlockAndPackagesAndVotesAtHeight(height uint64) error {
return d.DB.Transaction(func(dbTx *gorm.DB) error {
err := dbTx.Where("height = ?", height).Delete(model.BscBlock{}).Error
if err != nil {
Expand All @@ -152,6 +153,10 @@ func (d *BSCDao) DeleteBlockAndPackagesAtHeight(height uint64) error {
if err != nil {
return err
}
err = dbTx.Where("height = ? and event_type = ?", height, votepool.FromOpCrossChainEvent).Delete(model.Vote{}).Error
if err != nil {
return err
}
return nil
})
}
Expand Down
26 changes: 13 additions & 13 deletions executor/bsc_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,15 +240,22 @@ func (e *BSCExecutor) UpdateClientLoop() {
config.SendTelegramMessage(e.config.AlertConfig.Identity, e.config.AlertConfig.TelegramBotId,
e.config.AlertConfig.TelegramChatId, msg)
}
height, err := e.getLatestBlockHeight(bscClient.ethClient, bscClient.rpcClient, true)
var (
height uint64
err error
)
if e.config.BSCConfig.IsOpCrossChain() {
height, err = e.GetLatestBlockHeightWithRetry()
} else {
height, err = e.GetLatestFinalizedBlockHeightWithRetry()
}
if err != nil {
logging.Logger.Errorf("get latest block height error, err=%s", err.Error())
continue
}
bscClient.height = height
bscClient.updatedAt = time.Now()
}

highestHeight := uint64(0)
highestIdx := 0
for idx := 0; idx < len(e.bscClients); idx++ {
Expand Down Expand Up @@ -355,14 +362,10 @@ func (e *BSCExecutor) getTransactor(nonce uint64) (*bind.TransactOpts, error) {
txOpts.Nonce = big.NewInt(int64(nonce))
txOpts.Value = big.NewInt(0)
txOpts.GasLimit = e.config.BSCConfig.GasLimit
txOpts.GasPrice = e.getGasPrice()
txOpts.GasPrice = e.gasPrice
return txOpts, nil
}

func (e *BSCExecutor) getGasPrice() *big.Int {
return e.gasPrice
}

func (e *BSCExecutor) SyncTendermintLightBlock(height uint64) (common.Hash, error) {
ctx, cancel := context.WithTimeout(context.Background(), RPCTimeout)
defer cancel()
Expand Down Expand Up @@ -461,11 +464,7 @@ func (e *BSCExecutor) QueryCachedLatestValidators() ([]rtypes.Validator, error)
if len(e.relayers) != 0 {
return e.relayers, nil
}
relayers, err := e.QueryLatestValidators()
if err != nil {
return nil, err
}
return relayers, nil
return e.QueryLatestValidators()
}

func (e *BSCExecutor) UpdateCachedLatestValidatorsLoop() {
Expand Down Expand Up @@ -571,7 +570,8 @@ func (e *BSCExecutor) ClaimRewardLoop() {
continue
}
logging.Logger.Infof("current relayer balance is %v", balance)
balance.Div(balance, BSCBalanceThreshold)
balance.Div(balance, BNBDecimal)

e.metricService.SetBSCBalance(float64(balance.Int64()))

// should not claim if balance > 1 BNB
Expand Down
5 changes: 3 additions & 2 deletions executor/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ const (
)

var (
BSCBalanceThreshold = big.NewInt(1000000000000000000) // when relayer is lower than 1BNB, it should try to claim rewards
BSCRewardThreshold = big.NewInt(100000000000000000) // if reward is lower than 0.1 BNB, it will not be claimed.
BSCBalanceThreshold = big.NewInt(1) // when relayer is lower than 1BNB, it should try to claim rewards
BNBDecimal = big.NewInt(1000000000000000000)

BSCRewardThreshold = big.NewInt(100000000000000000) // if reward is lower than 0.1 BNB, it will not be claimed.
)
6 changes: 4 additions & 2 deletions executor/greenfield_executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,10 +337,12 @@ func (e *GreenfieldExecutor) ClaimPackages(client *GreenfieldClient, payloadBts
return txRes.TxHash, nil
}

func (e *GreenfieldExecutor) GetInturnRelayer() (*oracletypes.QueryInturnRelayerResponse, error) {
func (e *GreenfieldExecutor) GetInturnRelayer(srcChain oracletypes.ClaimSrcChain) (*oracletypes.QueryInturnRelayerResponse, error) {
ctx, cancel := context.WithTimeout(context.Background(), RPCTimeout)
defer cancel()
return e.GetGnfdClient().GetInturnRelayer(ctx, &oracletypes.QueryInturnRelayerRequest{})
return e.GetGnfdClient().GetInturnRelayer(ctx, &oracletypes.QueryInturnRelayerRequest{
ClaimSrcChain: srcChain,
})
}

func (e *GreenfieldExecutor) QueryVotesByEventHashAndType(eventHash []byte, eventType votepool.EventType) ([]*votepool.Vote, error) {
Expand Down
28 changes: 17 additions & 11 deletions executor/greenfield_executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"encoding/hex"
sdk "github.com/cosmos/cosmos-sdk/types"
oracletypes "github.com/cosmos/cosmos-sdk/x/oracle/types"
"testing"

cbfttypes "github.com/cometbft/cometbft/types"
Expand Down Expand Up @@ -39,7 +40,11 @@ func TestGetNextSendSequenceForChannel(t *testing.T) {

func TestGetInturnRelayer(t *testing.T) {
e := GnfdExecutor()
relayer, err := e.GetInturnRelayer()
relayer, err := e.GetInturnRelayer(oracletypes.CLAIM_SRC_CHAIN_BSC)
require.NoError(t, err)
t.Log(relayer)

relayer, err = e.GetInturnRelayer(oracletypes.CLAIM_SRC_CHAIN_OP_BNB)
require.NoError(t, err)
t.Log(relayer)
}
Expand All @@ -59,29 +64,30 @@ func TestGetLatestValidators(t *testing.T) {

func TestGetConsensusStatus(t *testing.T) {
e := GnfdExecutor()
validators, err := e.GetGnfdClient().GetValidatorsByHeight(context.Background(), 1)
height := int64(1)
validators, err := e.GetGnfdClient().GetValidatorsByHeight(context.Background(), height)
assert.NoError(t, err)
b, _, err := e.GetBlockAndBlockResultAtHeight(1)
b, _, err := e.GetBlockAndBlockResultAtHeight(height)
assert.NoError(t, err)
t.Logf("NexValidator Hash: %s", hex.EncodeToString(b.NextValidatorsHash))
t.Logf("NexValidator Hash: %s", hexutil.Encode(b.NextValidatorsHash))
for i, validator := range validators {
t.Logf("validator %d", i)
t.Logf("validator pubkey %s", hexutil.Encode(validator.PubKey.Bytes()))
t.Logf("validator votingpower %d", validator.VotingPower)
t.Logf("relayeraddress %s", hex.EncodeToString(validator.RelayerAddress))
t.Logf("relayer bls pub key %s", hex.EncodeToString(validator.BlsKey))
t.Logf("relayeraddress %s", hexutil.Encode(validator.RelayerAddress))
t.Logf("relayer bls pub key %s", hexutil.Encode(validator.BlsKey))
}
cs, err := getCysString(e)
cs, err := getCysString(e, height)
assert.NoError(t, err)
t.Logf("consensus: %s", cs)
}

func getCysString(e *GreenfieldExecutor) (string, error) {
validators, err := e.GetGnfdClient().GetValidatorsByHeight(context.Background(), 1)
func getCysString(e *GreenfieldExecutor, height int64) (string, error) {
validators, err := e.GetGnfdClient().GetValidatorsByHeight(context.Background(), height)
if err != nil {
return "", err
}
block, err := e.GetGnfdClient().GetBlockByHeight(context.Background(), 1)
block, err := e.GetGnfdClient().GetBlockByHeight(context.Background(), height)
if err != nil {
return "", err
}
Expand All @@ -97,5 +103,5 @@ func getCysString(e *GreenfieldExecutor) (string, error) {
if err != nil {
return "", err
}
return hex.EncodeToString(csBytes), nil
return hexutil.Encode(csBytes), nil
}
28 changes: 15 additions & 13 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ go 1.20
require (
github.com/avast/retry-go/v4 v4.3.1
github.com/aws/aws-sdk-go v1.40.45
github.com/bnb-chain/greenfield v1.0.0
github.com/bnb-chain/greenfield-go-sdk v1.0.0
github.com/bnb-chain/greenfield v1.1.0
github.com/bnb-chain/greenfield-go-sdk v1.1.0
github.com/cometbft/cometbft v0.37.2
github.com/cosmos/cosmos-sdk v0.47.3
github.com/ethereum/go-ethereum v1.11.3
Expand Down Expand Up @@ -38,7 +38,7 @@ require (
github.com/armon/go-metrics v0.4.1 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect
github.com/bnb-chain/greenfield-common/go v0.0.0-20230830120314-a54ffd6da39f // indirect
github.com/bnb-chain/greenfield-common/go v0.0.0-20230906132736-eb2f0efea228 // indirect
github.com/btcsuite/btcd v0.23.3 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect
github.com/btcsuite/btcd/btcutil v1.1.3 // indirect
Expand Down Expand Up @@ -153,15 +153,17 @@ require (
github.com/zondax/hid v0.9.1 // indirect
github.com/zondax/ledger-go v0.14.1 // indirect
go.etcd.io/bbolt v1.3.7 // indirect
golang.org/x/crypto v0.10.0 // indirect
golang.org/x/crypto v0.14.0 // indirect
golang.org/x/exp v0.0.0-20230515195305-f3d0a9c9a5cc // indirect
golang.org/x/net v0.11.0 // indirect
golang.org/x/sys v0.9.0 // indirect
golang.org/x/term v0.9.0 // indirect
golang.org/x/text v0.10.0 // indirect
google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect
google.golang.org/grpc v1.56.1 // indirect
google.golang.org/protobuf v1.30.0 // indirect
golang.org/x/net v0.17.0 // indirect
golang.org/x/sys v0.13.0 // indirect
golang.org/x/term v0.13.0 // indirect
golang.org/x/text v0.13.0 // indirect
google.golang.org/genproto v0.0.0-20230711160842-782d3b101e98 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20230711160842-782d3b101e98 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20230711160842-782d3b101e98 // indirect
google.golang.org/grpc v1.58.3 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/natefinch/npipe.v2 v2.0.0-20160621034901-c1b8fa8bdcce // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
Expand All @@ -174,11 +176,11 @@ require (
replace (
cosmossdk.io/api => github.com/bnb-chain/greenfield-cosmos-sdk/api v0.0.0-20230816082903-b48770f5e210
cosmossdk.io/math => github.com/bnb-chain/greenfield-cosmos-sdk/math v0.0.0-20230816082903-b48770f5e210
github.com/cometbft/cometbft => github.com/bnb-chain/greenfield-cometbft v1.0.0
github.com/cometbft/cometbft => github.com/bnb-chain/greenfield-cometbft v1.1.0
github.com/cometbft/cometbft-db => github.com/bnb-chain/greenfield-cometbft-db v0.8.1-alpha.1
github.com/confio/ics23/go => github.com/cosmos/cosmos-sdk/ics23/go v0.8.0
github.com/consensys/gnark-crypto => github.com/consensys/gnark-crypto v0.7.0
github.com/cosmos/cosmos-sdk => github.com/bnb-chain/greenfield-cosmos-sdk v1.0.0
github.com/cosmos/cosmos-sdk => github.com/bnb-chain/greenfield-cosmos-sdk v1.1.0
github.com/cosmos/iavl => github.com/bnb-chain/greenfield-iavl v0.20.1
github.com/syndtr/goleveldb => github.com/syndtr/goleveldb v1.0.1-0.20210819022825-2ae1ddf74ef7
)
Loading

0 comments on commit ee9f492

Please sign in to comment.