Skip to content

Commit

Permalink
Merge branch 'main' of https://github.com/b2network/b2-node
Browse files Browse the repository at this point in the history
  • Loading branch information
robertcc committed Dec 15, 2023
2 parents f71b756 + eee3e1c commit 157a941
Show file tree
Hide file tree
Showing 9 changed files with 177 additions and 17 deletions.
7 changes: 4 additions & 3 deletions bitcoin/bridge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,17 +125,18 @@ func TestABIPack(t *testing.T) {
}
expectedMethod := "deposit"
expectedArgs := []interface{}{common.HexToAddress("0x12345678"), new(big.Int).SetInt64(1111)}
expectedResult := []byte{71, 231, 239, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
expectedResult := []byte{
71, 231, 239, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 18, 52, 86, 120, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 4, 87}
0, 0, 4, 87,
}

// Create a mock bridge object
b := &bitcoin.Bridge{}

// Call the ABIPack method
result, err := b.ABIPack(string(abiData), expectedMethod, expectedArgs...)

// Check for errors
if err != nil {
t.Errorf("Unexpected error: %v", err)
Expand Down
53 changes: 42 additions & 11 deletions bitcoin/commiter_service.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,35 @@
package bitcoin

import (
"crypto/rand" // #nosec G702
"strconv"
"time"

dbm "github.com/tendermint/tm-db"

"github.com/tendermint/tendermint/libs/service"
)

const (
BitcoinServiceName = "BitcoinCommitterService"

WaitTimeout = 10 * time.Minute
WaitTimeout = 1 * time.Minute
)

// CommitterService is a service that commits bitcoin transactions.
type CommitterService struct {
service.BaseService
committer *Committer
db dbm.DB
}

// NewIndexerService returns a new service instance.
func NewCommitterService(
committer *Committer,
db dbm.DB,
) *CommitterService {
is := &CommitterService{committer: committer}
is.BaseService = *service.NewBaseService(nil, BitcoinServiceName, is)
is.db = db
return is
}

Expand All @@ -36,19 +41,38 @@ func (bis *CommitterService) OnStart() error {
<-ticker.C
ticker.Reset(WaitTimeout)

dataList := make([]InscriptionData, 0)

b := make([]byte, 16)
_, err := rand.Read(b)
index := int64(0)
blockNumMax, err := bis.db.Get([]byte("blockNumMax"))
if err != nil {
bis.Logger.Error("rand.Read error", "err", err)
bis.Logger.Error("Failed to get blockNumMax", "err", err)
continue
}
if blockNumMax != nil {
index, err = strconv.ParseInt(string(blockNumMax), 10, 64)
if err != nil {
bis.Logger.Error("Failed to parse blockNumMax", "err", err)
continue
}
}

dataList = append(dataList, InscriptionData{
Body: b,
Destination: bis.committer.destination,
})
roots, err := GetStateRoot(bis.committer.stateConfig, index)
if err != nil {
bis.Logger.Error("Failed to get state root", "err", err)
continue
}
if roots == nil {
continue
}
dataList := make([]InscriptionData, 0)
for _, root := range roots {
dataList = append(dataList, InscriptionData{
Body: []byte(root.StateRoot),
Destination: bis.committer.destination,
})
if root.BlockNum > index {
index = root.BlockNum
}
}

req, err := NewRequest(bis.committer.client, dataList) // update latest block
if err != nil {
Expand Down Expand Up @@ -78,5 +102,12 @@ func (bis *CommitterService) OnStart() error {
bis.Logger.Info("inscriptions," + inscriptions[i])
}
bis.Logger.Info("fees:", "fee", fees)

indexStr := strconv.FormatInt(index, 10)
err = bis.db.Set([]byte("blockNumMax"), []byte(indexStr))
if err != nil {
bis.Logger.Error("Failed to set blockNumMax", "err", err)
continue
}
}
}
4 changes: 3 additions & 1 deletion bitcoin/committer.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ type Committer struct {
client *rpcclient.Client
chainParams *chaincfg.Params
destination string
stateConfig StateConfig
}

// BlockChainInfo gets the blockchain info
Expand All @@ -81,7 +82,7 @@ func (b *Committer) BlockChainInfo() (*btcjson.GetBlockChainInfoResult, error) {
}

// NewCommitter creates a new Committer
func NewCommitter(client *rpcclient.Client, network string, destination string) (*Committer, error) {
func NewCommitter(client *rpcclient.Client, network string, destination string, stateConfig StateConfig) (*Committer, error) {
if network == "" {
return nil, errors.New("committer network is empty")
}
Expand All @@ -104,6 +105,7 @@ func NewCommitter(client *rpcclient.Client, network string, destination string)
client: client,
chainParams: &params,
destination: destination,
stateConfig: stateConfig,
}, nil
}

Expand Down
10 changes: 10 additions & 0 deletions bitcoin/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ type BitconConfig struct {
IndexerListenAddress string `mapstructure:"indexer-listen-address"`
// Bridge defines the bridge config
Bridge BridgeConfig `mapstructure:"bridge"`
// Dsn defines the state db dsn
StateConfig StateConfig `mapstructure:"state"`
// SourceAddress defines the bitcoin send source address
SourceAddress string `mapstructure:"source-address"`
// Fee defines the bitcoin tx fee
Expand All @@ -72,6 +74,14 @@ type BridgeConfig struct {
AAKernelFactory string `mapstructure:"aa-kernel-factory"`
}

type StateConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
User string `mapstructure:"user"`
Pass string `mapstructure:"pass"`
DBName string `mapstructure:"db-name"`
}

type EvmConfig struct {
// EnableListener defines whether to enable the listener
EnableListener bool `mapstructure:"enable-listener"`
Expand Down
10 changes: 10 additions & 0 deletions bitcoin/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,11 @@ func TestConfigEnv(t *testing.T) {
os.Setenv("BITCOIN_BRIDGE_ETH_PRIV_KEY", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
os.Setenv("BITCOIN_BRIDGE_ABI", "aaa.abi")
os.Setenv("BITCOIN_BRIDGE_GAS_LIMIT", "23333")
os.Setenv("BITCOIN_STATE_HOST", "localhost")
os.Setenv("BITCOIN_STATE_PORT", "5432")
os.Setenv("BITCOIN_STATE_USER", "user")
os.Setenv("BITCOIN_STATE_PASS", "password")
os.Setenv("BITCOIN_STATE_DB_NAME", "db")
os.Setenv("BITCOIN_BRIDGE_AA_SCA_REGISTRY", "0xB457BF68D71a17Fa5030269Fb895e29e6cD2DF23")
os.Setenv("BITCOIN_BRIDGE_AA_KERNEL_FACTORY", "0xB457BF68D71a17Fa5030269Fb895e29e6cD2DF24")
config, err := bitcoin.LoadBitcoinConfig("./testdata")
Expand All @@ -81,6 +86,11 @@ func TestConfigEnv(t *testing.T) {
require.Equal(t, "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", config.Bridge.EthPrivKey)
require.Equal(t, "aaa.abi", config.Bridge.ABI)
require.Equal(t, uint64(23333), config.Bridge.GasLimit)
require.Equal(t, "localhost", config.StateConfig.Host)
require.Equal(t, 5432, config.StateConfig.Port)
require.Equal(t, "user", config.StateConfig.User)
require.Equal(t, "password", config.StateConfig.Pass)
require.Equal(t, "db", config.StateConfig.DBName)
require.Equal(t, "0xB457BF68D71a17Fa5030269Fb895e29e6cD2DF23", config.Bridge.AASCARegistry)
require.Equal(t, "0xB457BF68D71a17Fa5030269Fb895e29e6cD2DF24", config.Bridge.AAKernelFactory)
}
Expand Down
63 changes: 63 additions & 0 deletions bitcoin/state.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package bitcoin

import (
"context"
"database/sql"
"fmt"
"time"
)

func openDB(cfg StateConfig) (*sql.DB, error) {
dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
cfg.Host, cfg.Port, cfg.User, cfg.Pass, cfg.DBName)
db, err := sql.Open("postgres", dsn)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

err = db.PingContext(ctx)
if err != nil {
return nil, err
}
return db, nil
}

type VerifiedBatch struct {
BatchNum int64
TxHash string
Aggregator string
StateRoot string
BlockNum int64
IsTrusted bool
}

func GetStateRoot(cfg StateConfig, index int64) ([]*VerifiedBatch, error) {
db, err := openDB(cfg)
if err != nil {
return nil, fmt.Errorf("openDB err:%w", err)
}
userSQL := "select state_root, max(block_num) block_num from state.verified_batch where block_num > $1 and " +
" is_trusted=true group by state_root order by block_num desc"
rows, err := db.Query(userSQL, index)
if err != nil {
return nil, fmt.Errorf("vin parse err:%w", err)
}
var batchs []*VerifiedBatch

for rows.Next() {
var stateRoot string
var blockNum int64
err = rows.Scan(&stateRoot, &blockNum)
if err != nil {
return nil, fmt.Errorf("vin parse err:%w", err)
}
batch := &VerifiedBatch{
StateRoot: stateRoot,
BlockNum: blockNum,
}
batchs = append(batchs, batch)
}
return batchs, nil
}
25 changes: 25 additions & 0 deletions bitcoin/state_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package bitcoin_test

import (
"testing"

"github.com/evmos/ethermint/bitcoin"
_ "github.com/lib/pq"
"github.com/stretchr/testify/require"
)

func TestLocalGetStateRoot(t *testing.T) {
cfg := bitcoin.StateConfig{
Host: "localhost",
Port: 5432,
User: "state_user",
Pass: "state_password",
DBName: "state_db",
}
items, err := bitcoin.GetStateRoot(cfg, 1)
require.NoError(t, err)
for _, item := range items {
require.Equal(t, int64(1299), item.BlockNum)
require.Equal(t, "0x1cc9e812fdad14a03f6e3c8563393d0e0c155dbd1d54361f41b33da46b087294", item.StateRoot)
}
}
7 changes: 7 additions & 0 deletions bitcoin/testdata/bitcoin.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,10 @@ contract-address = "0x47549F0f902F8E0DB96aBb16E06Da60751516F54"
start-height = 0
deposit = "0x01bee1bfa4116bd0440a1108ef6cb6a2f6eb9b611d8f53260aec20d39e84ee88"
withdraw = "0xda335c6ae73006d1145bdcf9a98bc76d789b653b13fe6200e6fc4c5dd54add85"

[state]
host = "localhost"
port = 5432
user = "state_user"
pass = "state_password"
db-name = "state_db"
15 changes: 13 additions & 2 deletions server/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt
bclient.Shutdown()
}()
bidxLogger := ctx.Logger.With("committer", "bitcoin")
committer, err := bitcoin.NewCommitter(bclient, bitcoinCfg.NetworkName, bitcoinCfg.Destination)
committer, err := bitcoin.NewCommitter(bclient, bitcoinCfg.NetworkName, bitcoinCfg.Destination, bitcoinCfg.StateConfig)
if err != nil {
logger.Error("failed to new bitcoin committer", "error", err.Error())
return err
Expand All @@ -735,7 +735,13 @@ func startInProcess(ctx *server.Context, clientCtx client.Context, opts StartOpt
return err
}

committerService := bitcoin.NewCommitterService(committer)
citDB, err := OpenCommitterDB(home, server.GetAppDBBackend(ctx.Viper))
if err != nil {
logger.Error("failed to open evm indexer DB", "error", err.Error())
return err
}

committerService := bitcoin.NewCommitterService(committer, citDB)
committerService.SetLogger(bidxLogger)

errCh := make(chan error)
Expand Down Expand Up @@ -812,6 +818,11 @@ func OpenIndexerDB(rootDir string, backendType dbm.BackendType) (dbm.DB, error)
return dbm.NewDB("evmindexer", backendType, dataDir)
}

func OpenCommitterDB(rootDir string, backendType dbm.BackendType) (dbm.DB, error) {
dataDir := filepath.Join(rootDir, "data")
return dbm.NewDB("committer", backendType, dataDir)
}

func openTraceWriter(traceWriterFile string) (w io.Writer, err error) {
if traceWriterFile == "" {
return
Expand Down

0 comments on commit 157a941

Please sign in to comment.