Skip to content

Commit

Permalink
add btc process
Browse files Browse the repository at this point in the history
  • Loading branch information
zhouop0 committed Jan 31, 2024
1 parent afd0e3d commit 2f0f068
Show file tree
Hide file tree
Showing 13 changed files with 293 additions and 91 deletions.
17 changes: 10 additions & 7 deletions internal/handler/checkstatus.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,17 @@ func CheckStatusTimeOut(ctx *svc.ServiceContext) {
log.Errorf("[Handler.CheckStatusTimeOut] QueryProposalByID err: %s\n", errors.WithStack(err))
continue
}
num := uint64(ctx.LatestBlockNumber) - proposal.BlockHight
if num > 10000 {
err := ctx.NodeClient.TimeoutProposal(proposal.Id)
if err != nil {
log.Errorf("[Handler.CheckStatusTimeOut] TimeoutProposal err: %s\n", errors.WithStack(err))
continue
if proposal.BitcoinTxHash == "" && proposal.Status == schema.PendingStatus && proposal.Winner != ctx.B2NodeConfig.Address {
num := uint64(ctx.LatestBlockNumber) - proposal.BlockHight
if num > 10000 {
err := ctx.NodeClient.TimeoutProposal(proposal.Id)
if err != nil {
log.Errorf("[Handler.CheckStatusTimeOut] TimeoutProposal err: %s\n", errors.WithStack(err))
continue
}
}
time.Sleep(2 * time.Second)
}
time.Sleep(2 * time.Second)

}
}
32 changes: 21 additions & 11 deletions internal/handler/committer.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ type VerifyRangBatchInfo struct {
func Committer(ctx *svc.ServiceContext) {
for {
var proposals []schema.Proposal
lastFinalBatchNum, _, err := ctx.NodeClient.QueryLastProposalID()
lastProposalID, lastFinalBatchNum, err := ctx.NodeClient.QueryLastProposalID()
if err != nil {
log.Errorf("[Handler.inscribe][QueryLastProposalID] error info:", errors.WithStack(err))
time.Sleep(10 * time.Second)
Expand Down Expand Up @@ -83,7 +83,7 @@ func Committer(ctx *svc.ServiceContext) {
time.Sleep(10 * time.Second)
continue
}
err = committerProposal(ctx, verifyBatchInfo)
err = committerProposal(ctx, verifyBatchInfo, lastProposalID)
if err != nil {
log.Errorf("[Handler.inscribe] error info:", errors.WithStack(err))
time.Sleep(10 * time.Second)
Expand All @@ -94,11 +94,14 @@ func Committer(ctx *svc.ServiceContext) {
}

// CommitterProposal committer transaction to b2-node
func committerProposal(ctx *svc.ServiceContext, verifyBatchInfo *VerifyRangBatchInfo) error {
proposalID, _ := ctx.NodeClient.SubmitProof(0, ctx.B2NodeConfig.Address, verifyBatchInfo.proofRootHash, verifyBatchInfo.stateRootHash,
func committerProposal(ctx *svc.ServiceContext, verifyBatchInfo *VerifyRangBatchInfo, lastProposalID uint64) error {
proposalID, err := ctx.NodeClient.SubmitProof(lastProposalID+1, ctx.B2NodeConfig.Address, verifyBatchInfo.proofRootHash, verifyBatchInfo.stateRootHash,
verifyBatchInfo.startBatchNum, verifyBatchInfo.endBatchNum)
if err != nil {
return fmt.Errorf("[committerProposal] submit proof error info: %s", errors.WithStack(err))
}

proposal := &schema.Proposal{
dbProposal := &schema.Proposal{
Base: schema.Base{
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
Expand All @@ -112,7 +115,7 @@ func committerProposal(ctx *svc.ServiceContext, verifyBatchInfo *VerifyRangBatch
}

// store db
err := ctx.DB.Save(proposal).Error
err = ctx.DB.Save(dbProposal).Error
if err != nil {
return fmt.Errorf("[committerProposal] save proposal error info: %s", errors.WithStack(err))
}
Expand All @@ -124,16 +127,23 @@ func GetMerkleStateRootsAndProofs(params []*VerifyBatchesTrustedAggregatorParams
proofs := make([]string, 0, 10)
var startBatchNum uint64
var endBatchNum uint64
for _, param := range params {
if startBatchNum < param.initNumBatch {
for index, param := range params {
if index == 0 {
startBatchNum = param.initNumBatch
endBatchNum = param.finalNewBatch
}
if startBatchNum > param.initNumBatch {
startBatchNum = param.initNumBatch
}
if endBatchNum > param.finalNewBatch {
if endBatchNum <= param.finalNewBatch {
endBatchNum = param.finalNewBatch
}
stateRoots = append(stateRoots, param.newStateRoot)
proofs = append(proofs, param.proof)
}
if startBatchNum == 0 {
startBatchNum = 1
}
stateBlocks := merkle.GenerateBlocks(stateRoots)
proofBlocks := merkle.GenerateBlocks(proofs)

Expand Down Expand Up @@ -219,8 +229,8 @@ func GetVerifyBatchesParamsByTxHash(ctx *svc.ServiceContext, txHash common.Hash)
result += hex.EncodeToString(arr[:])
}

fmt.Printf("newStateRoot outputs: %v\n", hex.EncodeToString(f[:]))
fmt.Printf("proof outputs: %v\n", common.HexToHash(result))
log.Debugf("newStateRoot outputs: %v\n", hex.EncodeToString(f[:]))
log.Debugf("proof outputs: %v\n", common.HexToHash(result))

return &VerifyBatchesTrustedAggregatorParams{
pendingStateNum: inputsMap["pendingStateNum"].(uint64),
Expand Down
14 changes: 7 additions & 7 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ import (
)

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

Expand Down
44 changes: 19 additions & 25 deletions internal/handler/inscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package handler

import (
"encoding/json"
"github.com/b2network/b2committer/pkg/btcapi"
btcmempool "github.com/b2network/b2committer/pkg/btcapi/mempool"
"time"

"github.com/b2network/b2committer/pkg/inscribe"
Expand All @@ -10,7 +12,6 @@ import (

"github.com/b2network/b2committer/internal/schema"
"github.com/b2network/b2committer/internal/svc"
"github.com/btcsuite/btcd/chaincfg"
"github.com/pkg/errors"
)

Expand All @@ -32,12 +33,12 @@ func Inscribe(ctx *svc.ServiceContext) {
if proposal.Status == schema.SucceedStatus {
dbProposal.Status = proposal.Status
dbProposal.Winner = proposal.Winner
dbProposal.BitcoinRevealTxHash = proposal.BitcoinTxHash
dbProposal.BtcRevealTxHash = proposal.BitcoinTxHash
ctx.DB.Save(dbProposal)
}
if proposal.Status == schema.PendingStatus &&
proposal.Winner == ctx.B2NodeConfig.Address && proposal.BitcoinTxHash == "" {
rs, err := inscribe.Inscribe(ctx.BTCConfig.PrivateKey, proposal.StateRootHash, proposal.ProofHash, ctx.BTCConfig.DestinationAddress, ChainParams(ctx.BTCConfig.NetworkName))
rs, err := inscribe.Inscribe(ctx.BTCConfig.PrivateKey, proposal.StateRootHash, proposal.ProofHash, ctx.BTCConfig.DestinationAddress, btcapi.ChainParams(ctx.BTCConfig.NetworkName))
if err != nil {
log.Errorf("[Handler.Inscribe] Inscribe err: %s\n", errors.WithStack(err))
continue
Expand All @@ -55,34 +56,27 @@ func Inscribe(ctx *svc.ServiceContext) {
log.Errorf("[Handler.Inscribe] BitcoinTx err: %s\n", errors.WithStack(err))
continue
}
dbProposal.BitcoinRevealTxHash = bitcoinTxHash
dbProposal.BitcoinCommitTxHash = rs.CommitTxHash.String()
dbProposal.BtcRevealTxHash = bitcoinTxHash
dbProposal.BtcCommitTxHash = rs.CommitTxHash.String()

ctx.DB.Save(dbProposal)
}
if proposal.Status == schema.PendingStatus && proposal.BitcoinTxHash != "" {
_, err = ctx.NodeClient.BitcoinTx(proposal.Id, proposal.Proposer, proposal.BitcoinTxHash)
if proposal.Status == schema.PendingStatus && proposal.BitcoinTxHash != "" && proposal.Winner != ctx.B2NodeConfig.Address {
// 拿到bitcoin 去btc network query一下 确认状态 对比大于6个高度后 确认后就提交提案
btcAPIClient := btcmempool.NewClient(btcapi.ChainParams(ctx.BTCConfig.NetworkName))
transaction, err := btcAPIClient.GetTransactionByID(proposal.BitcoinTxHash)
if err != nil {
log.Errorf("[Handler.Inscribe] BitcoinTx err: %s\n", errors.WithStack(err))
log.Errorf("[Handler.Inscribe] GetTransactionByID err: %s\n", errors.WithStack(err))
continue
}
}
}
}
if transaction.Status.Confirmed && (ctx.LatestBTCBlockNumber-transaction.Status.BlockHeight) >= 6 {
_, err = ctx.NodeClient.BitcoinTx(proposal.Id, proposal.Proposer, proposal.BitcoinTxHash)
if err != nil {
log.Errorf("[Handler.Inscribe] BitcoinTx err: %s\n", errors.WithStack(err))
continue
}
}

func ChainParams(network string) *chaincfg.Params {
switch network {
case chaincfg.MainNetParams.Name:
return &chaincfg.MainNetParams
case chaincfg.TestNet3Params.Name:
return &chaincfg.TestNet3Params
case chaincfg.SigNetParams.Name:
return &chaincfg.SigNetParams
case chaincfg.SimNetParams.Name:
return &chaincfg.SimNetParams
case chaincfg.RegressionNetParams.Name:
return &chaincfg.RegressionNetParams
default:
return &chaincfg.TestNet3Params
}
}
}
12 changes: 12 additions & 0 deletions internal/handler/latestBlockNumber.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package handler

import (
"context"
"github.com/b2network/b2committer/pkg/btcapi"
btcmempool "github.com/b2network/b2committer/pkg/btcapi/mempool"
"time"

"github.com/b2network/b2committer/pkg/log"
Expand All @@ -19,6 +21,16 @@ func LatestBlackNumber(ctx *svc.ServiceContext) {
}
ctx.LatestBlockNumber = int64(latest)
log.Infof("[Handle.LatestBlackNumber] Syncing latest block number: %d \n", latest)

btcAPIClient := btcmempool.NewClient(btcapi.ChainParams(ctx.BTCConfig.NetworkName))
btcLatest, err := btcAPIClient.GetCurrentBlockHash()
if err != nil {
log.Errorf("[Handle.LatestBTCBlackNumber]Syncing btc network latest block number error: %s\n", err)
time.Sleep(3 * time.Second)
continue
}
ctx.LatestBTCBlockNumber = btcLatest
log.Infof("[Handle.LatestBTCBlackNumber] Syncing btc network latest block number: %d \n", btcLatest)
time.Sleep(3 * time.Second)
}
}
20 changes: 10 additions & 10 deletions internal/schema/proposal.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@ const (

type Proposal struct {
Base
ProposalID uint64 `json:"proposal_id"`
StateRootHash string `json:"state_root_hash"`
ProofRootHash string `json:"proof_root_hash"`
StartBatchNum uint64 `json:"start_batch_num"`
EndBatchNum uint64 `json:"end_batch_num"`
BitcoinRevealTxHash string `json:"btc_commit_tx_hash"`
BitcoinCommitTxHash string `json:"btc_reveal_tx_hash"`
BlockHeight uint64 `json:"block_height"`
Winner string `json:"winner"`
Status uint64 `json:"status"`
ProposalID uint64 `json:"proposal_id"`
StateRootHash string `json:"state_root_hash"`
ProofRootHash string `json:"proof_root_hash"`
StartBatchNum uint64 `json:"start_batch_num"`
EndBatchNum uint64 `json:"end_batch_num"`
BtcCommitTxHash string `json:"btc_commit_tx_hash"`
BtcRevealTxHash string `json:"btc_reveal_tx_hash"`
BlockHeight uint64 `json:"block_height"`
Winner string `json:"winner"`
Status uint64 `json:"status"`
}

func (Proposal) TableName() string {
Expand Down
21 changes: 11 additions & 10 deletions internal/svc/svc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,16 @@ import (
var svc *ServiceContext

type ServiceContext struct {
Config *types.Config
RPC *ethclient.Client
DB *gorm.DB
BTCConfig *types.BitcoinRPCConfig
B2NodeConfig *types.B2NODEConfig
LatestBlockNumber int64
SyncedBlockNumber int64
SyncedBlockHash common.Hash
NodeClient *b2node.NodeClient
Config *types.Config
RPC *ethclient.Client
DB *gorm.DB
BTCConfig *types.BitcoinRPCConfig
B2NodeConfig *types.B2NODEConfig
LatestBlockNumber int64
SyncedBlockNumber int64
SyncedBlockHash common.Hash
NodeClient *b2node.NodeClient
LatestBTCBlockNumber int64
}

func NewServiceContext(cfg *types.Config, bitcoinCfg *types.BitcoinRPCConfig, b2nodeConfig *types.B2NODEConfig) *ServiceContext {
Expand Down Expand Up @@ -60,7 +61,7 @@ func NewServiceContext(cfg *types.Config, bitcoinCfg *types.BitcoinRPCConfig, b2
if err != nil {
log.Panicf("[svc] init b2node grpc panic: %s\n", err)
}
nodeClient := b2node.NewNodeClient(privateKeHex, chainID, address, grpcConn)
nodeClient := b2node.NewNodeClient(privateKeHex, chainID, address, grpcConn, b2nodeConfig.RPCUrl)

svc = &ServiceContext{
BTCConfig: bitcoinCfg,
Expand Down
14 changes: 9 additions & 5 deletions internal/types/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,21 @@ type Config struct {
}

type B2NODEConfig struct {
PrivateKeyHex string `evn:"B2NODE_PRIVATE_KEY_HEX" envDefault:"ccfda99f572bd491c085e19986b6db234f7e1f8c6db3fc7a2eabb96615340ec5"`
Address string `env:"B2NODE_ADDRESS" envDefault:"ethm10ky5utnz5ddlmus5t2mm5ftxal3u0u6rsnx5nl"`
PrivateKeyHex string `evn:"B2NODE_PRIVATE_KEY_HEX" envDefault:"0c993419ff40521f20370c45721c92626c2f1fd35267258fb3d093ed0826b611"`
Address string `env:"B2NODE_ADDRESS" envDefault:"ethm1mffw0yzmusgm9fwd40jaal3vwustuhhx8rh03q"`
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"`
RPCUrl string `env:"RPC_URL" envDefault:"http://localhost:8545"`
}

type BitcoinRPCConfig struct {
NetworkName string `env:"NETWORK_NAME" envDefault:"testnet3"`
PrivateKey string `env:"BITCOIN_PRIVATE_KEY" envDefault:"f5d9aaa2c5ae280e153efcca934d9a022ad21dfd9ead2b203664f977dc90ec80"` // signet
DestinationAddress string `env:"COMMITTER_DESTINATION_ADDRESS" envDefault:"tb1pydyjgpezqp2q98ux0dc283d3wvt6c4mluvwxfxrsqcle2jz8vwysep55n5"`
NetworkName string `env:"NETWORK_NAME" envDefault:"signet"`
PrivateKey string `env:"BITCOIN_PRIVATE_KEY" envDefault:"c545a409ff7f2e66b4bc863a59dcccf0f4387668a92152a058446bcb58a57027"` // signet tb1p2rfzw7mdyvkashtls5z6y7e5wlwdfzvjyay9mk2xgsdmzt5zwykq2e0rq8
DestinationAddress string `env:"COMMITTER_DESTINATION_ADDRESS" envDefault:"tb1pvhr4e58yatk9uve22rr5umxs0jh9g0j0gtcj0ry2wf23lddhjptsf6c360"`
//c5b87dffa5ada5e75d72413cf5570a26f9a432b10ab3ef8708c00ca75b96dc74
//tb1pvhr4e58yatk9uve22rr5umxs0jh9g0j0gtcj0ry2wf23lddhjptsf6c360

}

var (
Expand Down
Loading

0 comments on commit 2f0f068

Please sign in to comment.