Skip to content

Commit

Permalink
format
Browse files Browse the repository at this point in the history
  • Loading branch information
zhouop0 committed Feb 5, 2024
1 parent 78c1c49 commit fb90a50
Show file tree
Hide file tree
Showing 9 changed files with 53 additions and 50 deletions.
3 changes: 2 additions & 1 deletion internal/handler/checkstatus.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,13 @@ func CheckStatus(ctx *svc.ServiceContext) {
dbProposal.BlockHeight = proposal.BlockHight
ctx.DB.Save(dbProposal)
}
time.Sleep(2 * time.Second)
time.Sleep(3 * time.Second)
}
}

func CheckStatusTimeOut(ctx *svc.ServiceContext) {
for {
time.Sleep(30 * time.Second)
var dbProposal schema.Proposal
err := ctx.DB.Where("status!=?", schema.SucceedStatus).Order("end_batch_num asc").First(&dbProposal).Error
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion internal/handler/committer.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ func GetMerkleStateRootsAndProofs(params []*VerifyBatchesTrustedAggregatorParams
func GetVerifyBatchesFromStartBatchNum(ctx *svc.ServiceContext, startBatchNum uint64, limit int) ([]*VerifyBatchesAndTxHash, error) {
events := make([]schema.SyncEvent, 0, limit)
err := ctx.DB.Table("sync_events").Select("*, JSON_EXTRACT(data, '$.numBatch') as numBatch").
Where("JSON_EXTRACT(data, '$.numBatch') > ?", startBatchNum).Order("numBatch").Limit(limit).Find(&events).Error
Where("JSON_EXTRACT(data, '$.numBatch') >= ?", startBatchNum).Order("numBatch").Limit(limit).Find(&events).Error
if err != nil {
return nil, fmt.Errorf("[GetVerifyBatchesFromStartBatchNum] dbbase err: %s", err)
}
Expand Down
37 changes: 14 additions & 23 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,20 @@ import (
)

func Run(ctx *svc.ServiceContext) {
//// 最新高度
//go LatestBlackNumber(ctx)
//// 同步区块
//go SyncBlock(ctx)
//// 同步事件
//go SyncEvent(ctx)
//// 执行committer
//go Committer(ctx)
//// 检查vote状态
//go CheckStatus(ctx)
//// 检查并铭刻
//go Inscribe(ctx)
//// check time out
//go CheckStatusTimeOut(ctx)
// query last block number
go LatestBlackNumber(ctx)
// sync blocks
go SyncBlock(ctx)
// sync events
go SyncEvent(ctx)
// execute committer
go Committer(ctx)

go CheckStatus(ctx)
// check and inscribe
go Inscribe(ctx)
// check time out
go CheckStatusTimeOut(ctx)
// sync proposal
go SyncProposal(ctx)

//// 检查
// go CheckBlock(ctx)
//// 迁移Block
// go MigrateBlock(ctx)
//// 迁移Event
// go MigrateEvent(ctx)
//// 处理syncTask
// go SyncTask(ctx)
}
4 changes: 3 additions & 1 deletion internal/handler/inscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (

// Inscribe check proposal statues. process pending proposal.
func Inscribe(ctx *svc.ServiceContext) {
time.Sleep(30 * time.Second)
for {
var dbProposal schema.Proposal
err := ctx.DB.Where("status=?", schema.PendingStatus).Order("end_batch_num asc").First(&dbProposal).Error
Expand Down Expand Up @@ -52,7 +53,7 @@ func Inscribe(ctx *svc.ServiceContext) {
log.Infof("[Handler.Inscribe] inscribe result: %s", str)
bitcoinTxHash := rs.RevealTxHashList[0].String()

_, err = ctx.NodeClient.BitcoinTx(proposal.Id, proposal.Proposer, bitcoinTxHash)
_, err = ctx.NodeClient.BitcoinTx(proposal.Id, proposal.Winner, bitcoinTxHash)
if err != nil {
log.Errorf("[Handler.Inscribe] BitcoinTx err: %s\n", errors.WithStack(err))
continue
Expand All @@ -78,5 +79,6 @@ func Inscribe(ctx *svc.ServiceContext) {
}
}
}
time.Sleep(10 * time.Second)
}
}
29 changes: 15 additions & 14 deletions internal/handler/syncProposal.go
Original file line number Diff line number Diff line change
@@ -1,64 +1,66 @@
package handler

import (
"time"

"github.com/b2network/b2committer/internal/schema"
"github.com/b2network/b2committer/internal/svc"
"github.com/b2network/b2committer/pkg/log"
"github.com/pkg/errors"
"time"
"gorm.io/gorm"
)

// SyncProposal sync proposal and process voting status
func SyncProposal(ctx *svc.ServiceContext) {
time.Sleep(10 * time.Second)
proposalId := uint64(1) //自定义
proposalID := ctx.Config.InitProposalID
for {
lastProposalID, _, err := ctx.NodeClient.QueryLastProposalID()
if err != nil {
log.Errorf("[Handler.Committer][QueryLastProposalID] error info:", errors.WithStack(err))
time.Sleep(3 * time.Second)
continue
}
if lastProposalID < proposalId {
if lastProposalID < proposalID {
log.Infof("[Handler.SyncProposal] Current proposalId is latest")
time.Sleep(30 * time.Second)
continue
}

proposal, err := ctx.NodeClient.QueryProposalByID(proposalId)
proposal, err := ctx.NodeClient.QueryProposalByID(proposalID)
if err != nil {
log.Errorf("[Handler.SyncProposal] proposal QueryProposalByID error info:", errors.WithStack(err))
time.Sleep(3 * time.Second)
continue
}
if proposal == nil {
log.Infof("[Handler.SyncProposal] proposal is nil", proposalId)
proposalId++
log.Infof("[Handler.SyncProposal] proposal is nil", proposalID)
proposalID++
continue
}
var dbProposal schema.Proposal
err = ctx.DB.Where("proposal_id = ?", proposalId).Order("proposal_id desc").First(&dbProposal).Error
if err != nil {
err = ctx.DB.Where("proposal_id = ?", proposalID).Order("proposal_id desc").First(&dbProposal).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
log.Errorf("[Handler.SyncProposal] db query error info:", errors.WithStack(err))
time.Sleep(3 * time.Second)
continue
}
if dbProposal.ProposalID != 0 {
log.Infof("[Handler.SyncProposal] already voted :", ctx.B2NodeConfig.Address)
proposalId++
proposalID++
continue
}

if proposal.Status == schema.VotingStatus {
// voting
verifyBatchInfo, err := GetVerifyBatchInfoByLastBatchNum(ctx, proposal.EndIndex)
verifyBatchInfo, err := GetVerifyBatchInfoByLastBatchNum(ctx, proposal.StartIndex)
if err != nil {
log.Errorf("[Handler.SyncProposal] GetVerifyBatchInfoByLastBatchNum error info:", errors.WithStack(err))
time.Sleep(3 * time.Second)
continue
}

_, err = ctx.NodeClient.SubmitProof(lastProposalID+1, ctx.B2NodeConfig.Address, verifyBatchInfo.proofRootHash, verifyBatchInfo.stateRootHash,
_, err = ctx.NodeClient.SubmitProof(proposal.Id, ctx.B2NodeConfig.Address, verifyBatchInfo.proofRootHash, verifyBatchInfo.stateRootHash,
verifyBatchInfo.startBatchNum, verifyBatchInfo.endBatchNum)
if err != nil {
log.Errorf("[Handler.SyncProposal] vote proposal error info", errors.WithStack(err))
Expand Down Expand Up @@ -87,10 +89,9 @@ func SyncProposal(ctx *svc.ServiceContext) {
time.Sleep(3 * time.Second)
continue
}
proposalId++
proposalID++
continue
}

time.Sleep(10 * time.Second)
}

}
7 changes: 4 additions & 3 deletions internal/types/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type Config struct {
LogLevel string `env:"LOG_LEVEL" envDefault:"info"`
// "console","json"
LogFormat string `env:"LOG_FORMAT" envDefault:"console"`
MySQLDataSource string `env:"MYSQL_DATA_SOURCE" envDefault:"root:root@tcp(127.0.0.1:3306)/b2_committer2?charset=utf8mb4&parseTime=True&loc=Local&multiStatements=true"`
MySQLDataSource string `env:"MYSQL_DATA_SOURCE" envDefault:"root:root@tcp(127.0.0.1:3306)/b2_committer?charset=utf8mb4&parseTime=True&loc=Local&multiStatements=true"`
MySQLMaxIdleConns int `env:"MYSQL_MAX_IDLE_CONNS" envDefault:"10"`
MySQLMaxOpenConns int `env:"MYSQL_MAX_OPEN_CONNS" envDefault:"20"`
MySQLConnMaxLifetime int `env:"MYSQL_CONN_MAX_LIFETIME" envDefault:"3600"`
Expand All @@ -20,11 +20,12 @@ type Config struct {
InitBlockHash string `env:"INIT_BLOCK_HASH" envDefault:"0x1810ba2a2f66977cc45ad0ef6895393eff479ccfbb854bc8f4aa8154787c1144"`
PolygonZKEVMAddress string `env:"POLYGON_ZKEVM_ADDRESS" envDefault:"0x67d269191c92Caf3cD7723F116c85e6E9bf55933"`
LimitNum int `evn:"PROPOSAL_BATCHES_LIMITNUM" envDefault:"10"`
InitProposalID uint64 `evn:"INIT_PROPOSAL_ID" envDefault:"1"`
}

type B2NODEConfig struct {
PrivateKeyHex string `evn:"B2NODE_PRIVATE_KEY_HEX" envDefault:"7cf553484271fedfa04b8dab3c4b7a06f1ed10bfda24dbde615ed22c890afbc3"`
Address string `env:"B2NODE_ADDRESS" envDefault:"ethm1yz4g5svztygcvsen5whhlsa40uccwwtg3c9pdk"`
PrivateKeyHex string `evn:"B2NODE_PRIVATE_KEY_HEX" envDefault:"37927fcde10259a7114a58487cb6303d04c33291ba29bbb8e488eef150e6a59a"`
Address string `env:"B2NODE_ADDRESS" envDefault:"ethm1nexknt73vdv6cm3h6ep6u7pe9vg8kr6kqwyl0a"`
ChainID string `env:"B2NODE_CHAIN_ID" envDefault:"ethermint_9000-1"`
GRPCHost string `env:"B2NODE_GRPC_HOST" envDefault:"127.0.0.1"`
GRPCPort uint32 `env:"B2NODE_GRPC_PORT" envDefault:"9090"`
Expand Down
7 changes: 6 additions & 1 deletion pkg/b2node/b2node.go
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,11 @@ func (n NodeClient) BitcoinTx(proposalID uint64, from string, bitcoinTxHash stri
if err != nil {
return 0, fmt.Errorf("[BitcoinTx] err: %s", err)
}
code := msgResponse.TxResponse.Code
rawLog := msgResponse.TxResponse.RawLog
if code != 0 {
return 0, fmt.Errorf("[BitcoinTx][msgResponse.TxResponse.Code] err: %s", rawLog)
}
hexData := msgResponse.TxResponse.Data
byteData, err := hex.DecodeString(hexData)
if err != nil {
Expand Down Expand Up @@ -248,7 +253,7 @@ func (n NodeClient) buildSimTx(gasPrice uint64, msgs ...sdk.Msg) ([]byte, error)

func (n NodeClient) QueryLastProposalID() (uint64, uint64, error) {
queryClient := committerTypes.NewQueryClient(n.GrpcConn)
res, err := queryClient.LastProposalId(context.Background(), &committerTypes.QueryLastProposalIdRequest{})
res, err := queryClient.LastProposalID(context.Background(), &committerTypes.QueryLastProposalIdRequest{})
if err != nil {
return 0, 0, fmt.Errorf("[QueryLastProposalID] err: %s", err)
}
Expand Down
13 changes: 7 additions & 6 deletions pkg/b2node/b2node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ package b2node
import (
"encoding/hex"
"fmt"
"testing"

sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
"testing"

"github.com/b2network/b2committer/internal/types"
xcommitterTypes "github.com/evmos/ethermint/x/committer/types"
Expand Down Expand Up @@ -45,8 +46,8 @@ func TestSubmitProof(t *testing.T) {

func TestDecodeTxResponseData(t *testing.T) {
byteData, _ := hex.DecodeString("12370A312F65766D6F732E65746865726D696E742E636F6D6D69747465722E4D73675375626D697450726F6F66526573706F6E736512020808")
var pbMsg = &sdk.TxMsgData{}
//proto.Marshal(&sdk.TxMsgData{MsgResponses: msgResponses})
pbMsg := &sdk.TxMsgData{}
// proto.Marshal(&sdk.TxMsgData{MsgResponses: msgResponses})
pbMsg.Unmarshal(byteData)
fmt.Println(pbMsg.MsgResponses[0].TypeUrl)
resMsgRes := &xcommitterTypes.MsgSubmitProofResponse{}
Expand Down Expand Up @@ -125,16 +126,16 @@ func TestGetGasPrice(t *testing.T) {
}

func TestAddCommitter(t *testing.T) {
privateKeHex := "0bca05e42968d16e52c1ea996068fa3cfa3a08a8b6afdf506f19c46b56caea04"
privateKeHex := "37927fcde10259a7114a58487cb6303d04c33291ba29bbb8e488eef150e6a59a"
chainID := "ethermint_9000-1"
address := "ethm1jcf9exvr970jjc4efzsdh4y4pa698mmkpn5y6m"
address := "ethm1nexknt73vdv6cm3h6ep6u7pe9vg8kr6kqwyl0a"
rpcUrl := "http://localhost:8545"
grpcConn, err := types.GetClientConnection("127.0.0.1", types.WithClientPortOption(9090))
if err != nil {
panic(err)
}
nodeClient := NewNodeClient(privateKeHex, chainID, address, grpcConn, rpcUrl)
add, err := nodeClient.AddCommitter("ethm1yz4g5svztygcvsen5whhlsa40uccwwtg3c9pdk")
add, err := nodeClient.AddCommitter("ethm1c3csplac80qt22p5qwx3l5telv6ge9ycmzwe3w")
require.NoError(t, err)
fmt.Println(add)
}
1 change: 1 addition & 0 deletions pkg/inscribe/inscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ func Inscribe(privateKeyHex string, stateRootHash string, proofRootHash string,
Body: []byte(stateRootHash + proofRootHash),
Destination: destination,
})
fmt.Println(utxoTaprootAddress.EncodeAddress())
req, err := NewInscriptionRequest(btcAPIClient, utxoTaprootAddress, utxoPrivateKey, dataList)
if err != nil {
return nil, fmt.Errorf("create inscription request error: %w", err)
Expand Down

0 comments on commit fb90a50

Please sign in to comment.