diff --git a/go.work b/go.work index 5b76593e4..dcfda317e 100644 --- a/go.work +++ b/go.work @@ -18,8 +18,8 @@ use ( ) replace ( - github.com/Layr-Labs/datalayr/common v0.0.0 => ./datalayr/common - github.com/Layr-Labs/datalayr/lib/merkzg v0.0.0 => ./datalayr/lib/merkzg + // github.com/Layr-Labs/datalayr/common v0.0.0 => ./datalayr/common + // github.com/Layr-Labs/datalayr/lib/merkzg v0.0.0 => ./datalayr/lib/merkzg github.com/ethereum/go-ethereum v1.10.21 => github.com/ethereum-mantle/reference-optimistic-geth v0.0.0-20220803173305-1c9d4cc76a6e github.com/mantlenetworkio/mantle/bss-core v0.0.0 => ./bss-core github.com/mantlenetworkio/mantle/fraud-proof v0.0.0 => ./fraud-proof diff --git a/mt-batcher/common/utils.go b/mt-batcher/common/utils.go index bd02cc9d2..632d0cc9b 100644 --- a/mt-batcher/common/utils.go +++ b/mt-batcher/common/utils.go @@ -4,32 +4,31 @@ import ( "fmt" "math/big" "os" - - "github.com/Layr-Labs/datalayr/common/header" ) func CreateUploadHeader(params StoreParams) ([]byte, error) { - var kzgCommitArray [64]byte - copy(kzgCommitArray[:], params.KzgCommit) - var lowDegreeProof [64]byte - copy(lowDegreeProof[:], params.LowDegreeProof) - var disperserArray [20]byte - copy(disperserArray[:], params.Disperser) - - h := header.DataStoreHeader{ - KzgCommit: kzgCommitArray, - LowDegreeProof: lowDegreeProof, - Degree: params.Degree, - NumSys: params.NumSys, - NumPar: params.NumPar, - OrigDataSize: params.OrigDataSize, - Disperser: disperserArray, - } - uploadHeader, _, err := header.CreateUploadHeader(h) - if err != nil { - return nil, err - } - return uploadHeader, nil + //var kzgCommitArray [64]byte + //copy(kzgCommitArray[:], params.KzgCommit) + //var lowDegreeProof [64]byte + //copy(lowDegreeProof[:], params.LowDegreeProof) + //var disperserArray [20]byte + //copy(disperserArray[:], params.Disperser) + // + //h := header.DataStoreHeader{ + // KzgCommit: kzgCommitArray, + // LowDegreeProof: lowDegreeProof, + // Degree: params.Degree, + // NumSys: params.NumSys, + // NumPar: params.NumPar, + // OrigDataSize: params.OrigDataSize, + // Disperser: disperserArray, + //} + //uploadHeader, _, err := header.CreateUploadHeader(h) + //if err != nil { + // return nil, err + //} + //return uploadHeader, nil + return nil, nil } func uint32ToByteSlice(x uint32) []byte { diff --git a/mt-batcher/config.go b/mt-batcher/config.go index ceec8000b..b8d2dd519 100644 --- a/mt-batcher/config.go +++ b/mt-batcher/config.go @@ -3,7 +3,6 @@ package mt_batcher import ( "time" - "github.com/Layr-Labs/datalayr/common/logging" "github.com/mantlenetworkio/mantle/mt-batcher/flags" "github.com/urfave/cli" ) @@ -39,7 +38,7 @@ type Config struct { RollUpMinTxn uint64 RollUpMaxSize uint64 EigenLayerNode int - EigenLogConfig logging.Config + //EigenLogConfig logging.Config MetricsServerEnable bool MetricsHostname string MetricsPort uint64 @@ -102,7 +101,7 @@ func NewConfig(ctx *cli.Context) (Config, error) { RollUpMinTxn: ctx.GlobalUint64(flags.RollUpMinTxnFlag.Name), RollUpMaxSize: ctx.GlobalUint64(flags.RollUpMaxSizeFlag.Name), EigenLayerNode: ctx.GlobalInt(flags.EigenLayerNodeFlag.Name), - EigenLogConfig: logging.ReadCLIConfig(ctx), + //EigenLogConfig: logging.ReadCLIConfig(ctx), RetrieverTimeout: ctx.GlobalDuration(flags.RetrieverTimeoutFlag.Name), ResubmissionTimeout: ctx.GlobalDuration(flags.ResubmissionTimeoutFlag.Name), NumConfirmations: ctx.GlobalUint64(flags.NumConfirmationsFlag.Name), diff --git a/mt-batcher/go.mod b/mt-batcher/go.mod index bbc48f905..7b0d82103 100644 --- a/mt-batcher/go.mod +++ b/mt-batcher/go.mod @@ -2,9 +2,9 @@ module github.com/mantlenetworkio/mantle/mt-batcher go 1.19 -replace github.com/Layr-Labs/datalayr/common => ../datalayr/common - -replace github.com/Layr-Labs/datalayr/lib/merkzg => ../datalayr/lib/merkzg +//replace github.com/Layr-Labs/datalayr/common => ../datalayr/common +// +//replace github.com/Layr-Labs/datalayr/lib/merkzg => ../datalayr/lib/merkzg replace github.com/mantlenetworkio/mantle/l2geth => ../l2geth @@ -16,7 +16,7 @@ replace github.com/mantlenetworkio/mantle/bss-core => ../bss-core require ( cloud.google.com/go/kms v1.11.0 - github.com/Layr-Labs/datalayr/common v0.0.0 + //github.com/Layr-Labs/datalayr/common v0.0.0 github.com/decred/dcrd/hdkeychain/v3 v3.0.0 github.com/ethereum/go-ethereum v1.10.26 github.com/go-resty/resty/v2 v2.7.0 diff --git a/mt-batcher/mt_batcher.go b/mt-batcher/mt_batcher.go index 306227bdc..e4532795a 100644 --- a/mt-batcher/mt_batcher.go +++ b/mt-batcher/mt_batcher.go @@ -18,7 +18,6 @@ import ( "github.com/mantlenetworkio/mantle/mt-batcher/services/restorer" "github.com/mantlenetworkio/mantle/mt-batcher/services/sequencer" - "github.com/Layr-Labs/datalayr/common/logging" "github.com/urfave/cli" ) @@ -96,10 +95,10 @@ func NewMantleBatch(cfg Config) (*MantleBatch, error) { return nil, err } - logger, err := logging.GetLogger(cfg.EigenLogConfig) - if err != nil { - return nil, err - } + //logger, err := logging.GetLogger(cfg.EigenLogConfig) + //if err != nil { + // return nil, err + //} parsed, err := abi.JSON(strings.NewReader( bindings.BVMEigenDataLayrChainABI, )) @@ -135,18 +134,18 @@ func NewMantleBatch(cfg Config) (*MantleBatch, error) { ) driverConfig := &sequencer.DriverConfig{ - L1Client: l1Client, - L2Client: l2Client, - L1ChainID: chainID, - DtlClientUrl: cfg.DtlClientUrl, - EigenDaContract: eigenContract, - RawEigenContract: rawEigenContract, - EigenFeeContract: eigenFeeContract, - RawEigenFeeContract: rawEigenFeeContract, - FeeModelEnable: cfg.FeeModelEnable, - FeeSizeSec: cfg.FeeSizeSec, - FeePerBytePerTime: cfg.FeePerBytePerTime, - Logger: logger, + L1Client: l1Client, + L2Client: l2Client, + L1ChainID: chainID, + DtlClientUrl: cfg.DtlClientUrl, + EigenDaContract: eigenContract, + RawEigenContract: rawEigenContract, + EigenFeeContract: eigenFeeContract, + RawEigenFeeContract: rawEigenFeeContract, + FeeModelEnable: cfg.FeeModelEnable, + FeeSizeSec: cfg.FeeSizeSec, + FeePerBytePerTime: cfg.FeePerBytePerTime, + //Logger: logger, PrivKey: sequencerPrivKey, FeePrivKey: mtFeePrivateKey, BlockOffset: cfg.BlockOffset, diff --git a/mt-batcher/services/restorer/handle.go b/mt-batcher/services/restorer/handle.go index 7ba13d456..97badb3ef 100644 --- a/mt-batcher/services/restorer/handle.go +++ b/mt-batcher/services/restorer/handle.go @@ -1,28 +1,13 @@ package restorer import ( - "bytes" - "context" - "encoding/json" - "math/big" - "net/http" - "strings" - gecho "github.com/labstack/echo/v4" "github.com/pkg/errors" - "github.com/shurcooL/graphql" - "google.golang.org/grpc" - - "github.com/Layr-Labs/datalayr/common/graphView" - pb "github.com/Layr-Labs/datalayr/common/interfaces/interfaceRetrieverServer" + "math/big" + "net/http" "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - - common2 "github.com/mantlenetworkio/mantle/l2geth/common" "github.com/mantlenetworkio/mantle/l2geth/core/types" - l2rlp "github.com/mantlenetworkio/mantle/l2geth/rlp" "github.com/mantlenetworkio/mantle/l2geth/rollup/eigenda" ) @@ -86,211 +71,216 @@ func (s *DaService) GetRollupStoreByRollupBatchIndex(c gecho.Context) error { } func (s *DaService) GetBatchTransactionByDataStoreId(c gecho.Context) error { - var txReq TransactionRequest - if err := c.Bind(&txReq); err != nil { - log.Error("invalid request params", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) - } - conn, err := grpc.Dial(s.Cfg.RetrieverSocket, grpc.WithInsecure()) - if err != nil { - log.Error("disperser Cannot connect to", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("disperser Cannot connect to")) - } - defer conn.Close() - client := pb.NewDataRetrievalClient(conn) - - opt := grpc.MaxCallRecvMsgSize(maxCallReceiveMessageSize) - request := &pb.FramesAndDataRequest{ - DataStoreId: txReq.StoreNumber, - } - reply, err := client.RetrieveFramesAndData(s.Ctx, request, opt) - if err != nil { - log.Error("retrieve frames and data error", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("recovery data fail")) - } - if len(reply.GetData()) >= 31*s.Cfg.EigenLayerNode { - return c.JSON(http.StatusOK, reply.GetData()) - } else { - return c.JSON(http.StatusBadRequest, errors.New("retrieve data is empty, please check da date")) - } + //var txReq TransactionRequest + //if err := c.Bind(&txReq); err != nil { + // log.Error("invalid request params", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) + //} + //conn, err := grpc.Dial(s.Cfg.RetrieverSocket, grpc.WithInsecure()) + //if err != nil { + // log.Error("disperser Cannot connect to", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("disperser Cannot connect to")) + //} + //defer conn.Close() + //client := pb.NewDataRetrievalClient(conn) + // + //opt := grpc.MaxCallRecvMsgSize(maxCallReceiveMessageSize) + //request := &pb.FramesAndDataRequest{ + // DataStoreId: txReq.StoreNumber, + //} + //reply, err := client.RetrieveFramesAndData(s.Ctx, request, opt) + //if err != nil { + // log.Error("retrieve frames and data error", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("recovery data fail")) + //} + //if len(reply.GetData()) >= 31*s.Cfg.EigenLayerNode { + // return c.JSON(http.StatusOK, reply.GetData()) + //} else { + // return c.JSON(http.StatusBadRequest, errors.New("retrieve data is empty, please check da date")) + //} + return nil } func (s *DaService) GetDtlBatchTransactionByDataStoreId(c gecho.Context) error { - var txReq TransactionRequest - if err := c.Bind(&txReq); err != nil { - log.Error("invalid request params", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) - } - conn, err := grpc.Dial(s.Cfg.RetrieverSocket, grpc.WithInsecure()) - if err != nil { - log.Error("disperser Cannot connect to", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("disperser Cannot connect to")) - } - defer conn.Close() - client := pb.NewDataRetrievalClient(conn) - - opt := grpc.MaxCallRecvMsgSize(maxCallReceiveMessageSize) - request := &pb.FramesAndDataRequest{ - DataStoreId: txReq.StoreNumber, - } - reply, err := client.RetrieveFramesAndData(s.Ctx, request, opt) - if err != nil { - log.Error("retrieve frames and data error", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("recovery data fail")) - } - if len(reply.GetData()) >= 31*s.Cfg.EigenLayerNode { - data := reply.GetData() - - batchTxn := new([]eigenda.BatchTx) - batchRlpStream := rlp.NewStream(bytes.NewBuffer(data), uint64(len(data))) - err = batchRlpStream.Decode(batchTxn) - if err != nil { - return c.JSON(http.StatusBadRequest, errors.New("decode data fail")) - } - var TxnRep []*TransactionInfoListResponse - newBatchTxn := *batchTxn - for i := 0; i < len(newBatchTxn); i++ { - l2Tx := new(types.Transaction) - txDecodeMetaData := new(eigenda.TransactionMeta) - if newBatchTxn[i].TxMeta == nil { - log.Error("Batch tx metadata shouldn't be nil") - return c.JSON(http.StatusBadRequest, errors.New("Batch tx metadata shouldn't be nil")) - } - err = json.Unmarshal(newBatchTxn[i].TxMeta, txDecodeMetaData) - if err != nil { - return c.JSON(http.StatusBadRequest, errors.New("Unmarshal json fail")) - } - rlpStream := l2rlp.NewStream(bytes.NewBuffer(newBatchTxn[i].RawTx), 0) - if err := l2Tx.DecodeRLP(rlpStream); err != nil { - return c.JSON(http.StatusBadRequest, errors.New("Decode RLP fail")) - } - newBlockNumber := new(big.Int).SetBytes(newBatchTxn[i].BlockNumber) - - var queueOrigin types.QueueOrigin - var l1MessageSender *common2.Address - if txDecodeMetaData.QueueIndex == nil { - queueOrigin = types.QueueOriginSequencer - l1MessageSender = nil - } else { - queueOrigin = types.QueueOriginL1ToL2 - addrLs := common2.HexToAddress("") - l1MessageSender = &addrLs - } - realTxMeta := &types.TransactionMeta{ - L1BlockNumber: txDecodeMetaData.L1BlockNumber, - L1Timestamp: txDecodeMetaData.L1Timestamp, - L1MessageSender: l1MessageSender, - QueueOrigin: queueOrigin, - Index: txDecodeMetaData.Index, - QueueIndex: txDecodeMetaData.QueueIndex, - RawTransaction: txDecodeMetaData.RawTransaction, - } - txSl := &TransactionInfoListResponse{ - BlockNumber: newBlockNumber.String(), - TxHash: l2Tx.Hash().String(), - TxMeta: *realTxMeta, - TxData: *l2Tx, - } - TxnRep = append(TxnRep, txSl) - } - return c.JSON(http.StatusOK, TxnRep) - } else { - return c.JSON(http.StatusBadRequest, errors.New("retrieve data is empty, please check da date")) - } + //var txReq TransactionRequest + //if err := c.Bind(&txReq); err != nil { + // log.Error("invalid request params", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) + //} + //conn, err := grpc.Dial(s.Cfg.RetrieverSocket, grpc.WithInsecure()) + //if err != nil { + // log.Error("disperser Cannot connect to", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("disperser Cannot connect to")) + //} + //defer conn.Close() + //client := pb.NewDataRetrievalClient(conn) + // + //opt := grpc.MaxCallRecvMsgSize(maxCallReceiveMessageSize) + //request := &pb.FramesAndDataRequest{ + // DataStoreId: txReq.StoreNumber, + //} + //reply, err := client.RetrieveFramesAndData(s.Ctx, request, opt) + //if err != nil { + // log.Error("retrieve frames and data error", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("recovery data fail")) + //} + //if len(reply.GetData()) >= 31*s.Cfg.EigenLayerNode { + // data := reply.GetData() + // + // batchTxn := new([]eigenda.BatchTx) + // batchRlpStream := rlp.NewStream(bytes.NewBuffer(data), uint64(len(data))) + // err = batchRlpStream.Decode(batchTxn) + // if err != nil { + // return c.JSON(http.StatusBadRequest, errors.New("decode data fail")) + // } + // var TxnRep []*TransactionInfoListResponse + // newBatchTxn := *batchTxn + // for i := 0; i < len(newBatchTxn); i++ { + // l2Tx := new(types.Transaction) + // txDecodeMetaData := new(eigenda.TransactionMeta) + // if newBatchTxn[i].TxMeta == nil { + // log.Error("Batch tx metadata shouldn't be nil") + // return c.JSON(http.StatusBadRequest, errors.New("Batch tx metadata shouldn't be nil")) + // } + // err = json.Unmarshal(newBatchTxn[i].TxMeta, txDecodeMetaData) + // if err != nil { + // return c.JSON(http.StatusBadRequest, errors.New("Unmarshal json fail")) + // } + // rlpStream := l2rlp.NewStream(bytes.NewBuffer(newBatchTxn[i].RawTx), 0) + // if err := l2Tx.DecodeRLP(rlpStream); err != nil { + // return c.JSON(http.StatusBadRequest, errors.New("Decode RLP fail")) + // } + // newBlockNumber := new(big.Int).SetBytes(newBatchTxn[i].BlockNumber) + // + // var queueOrigin types.QueueOrigin + // var l1MessageSender *common2.Address + // if txDecodeMetaData.QueueIndex == nil { + // queueOrigin = types.QueueOriginSequencer + // l1MessageSender = nil + // } else { + // queueOrigin = types.QueueOriginL1ToL2 + // addrLs := common2.HexToAddress("") + // l1MessageSender = &addrLs + // } + // realTxMeta := &types.TransactionMeta{ + // L1BlockNumber: txDecodeMetaData.L1BlockNumber, + // L1Timestamp: txDecodeMetaData.L1Timestamp, + // L1MessageSender: l1MessageSender, + // QueueOrigin: queueOrigin, + // Index: txDecodeMetaData.Index, + // QueueIndex: txDecodeMetaData.QueueIndex, + // RawTransaction: txDecodeMetaData.RawTransaction, + // } + // txSl := &TransactionInfoListResponse{ + // BlockNumber: newBlockNumber.String(), + // TxHash: l2Tx.Hash().String(), + // TxMeta: *realTxMeta, + // TxData: *l2Tx, + // } + // TxnRep = append(TxnRep, txSl) + // } + // return c.JSON(http.StatusOK, TxnRep) + //} else { + // return c.JSON(http.StatusBadRequest, errors.New("retrieve data is empty, please check da date")) + //} + return nil } func (s *DaService) GetDataStoreList(c gecho.Context) error { - var dsReq DataStoreRequest - if err := c.Bind(&dsReq); err != nil { - log.Error("invalid request params", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) - } - var query struct { - DataStores []graphView.DataStoreGql `graphql:"dataStores(where:{storeNumber_gt: $lastStoreNumber,confirmer: $confirmer,confirmed:true})"` - } - variables := map[string]interface{}{ - "lastStoreNumber": graphql.String(dsReq.FromStoreNumber), - "confirmer": graphql.String(strings.ToLower(dsReq.EigenContractAddr)), - } - err := s.GraphqlClient.Query(context.Background(), &query, variables) - if err != nil { - log.Error("GetExpiringDataStores error") - return c.JSON(http.StatusBadRequest, errors.New("iGetExpiringDataStores error")) - } - if len(query.DataStores) == 0 { - return c.JSON(http.StatusBadRequest, errors.New("no new stores")) - } - return c.JSON(http.StatusOK, query.DataStores) + //var dsReq DataStoreRequest + //if err := c.Bind(&dsReq); err != nil { + // log.Error("invalid request params", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) + //} + //var query struct { + // DataStores []graphView.DataStoreGql `graphql:"dataStores(where:{storeNumber_gt: $lastStoreNumber,confirmer: $confirmer,confirmed:true})"` + //} + //variables := map[string]interface{}{ + // "lastStoreNumber": graphql.String(dsReq.FromStoreNumber), + // "confirmer": graphql.String(strings.ToLower(dsReq.EigenContractAddr)), + //} + //err := s.GraphqlClient.Query(context.Background(), &query, variables) + //if err != nil { + // log.Error("GetExpiringDataStores error") + // return c.JSON(http.StatusBadRequest, errors.New("iGetExpiringDataStores error")) + //} + //if len(query.DataStores) == 0 { + // return c.JSON(http.StatusBadRequest, errors.New("no new stores")) + //} + //return c.JSON(http.StatusOK, query.DataStores) + return nil } func (s *DaService) getDataStoreById(c gecho.Context) error { - var dsIdReq DataStoreIdRequest - if err := c.Bind(&dsIdReq); err != nil { - log.Error("invalid request params", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) - } - var query struct { - DataStore graphView.DataStoreGql `graphql:"dataStore(id: $storeId)"` - } - variables := map[string]interface{}{ - "storeId": graphql.String(dsIdReq.StoreId), - } - err := s.GraphqlClient.Query(context.Background(), &query, variables) - if err != nil { - log.Error("query data from graphql fail", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("query data from graphql fail")) - } - return c.JSON(http.StatusOK, query.DataStore) + //var dsIdReq DataStoreIdRequest + //if err := c.Bind(&dsIdReq); err != nil { + // log.Error("invalid request params", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) + //} + //var query struct { + // DataStore graphView.DataStoreGql `graphql:"dataStore(id: $storeId)"` + //} + //variables := map[string]interface{}{ + // "storeId": graphql.String(dsIdReq.StoreId), + //} + //err := s.GraphqlClient.Query(context.Background(), &query, variables) + //if err != nil { + // log.Error("query data from graphql fail", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("query data from graphql fail")) + //} + //return c.JSON(http.StatusOK, query.DataStore) + return nil } func (s *DaService) GetTransactionListByStoreNumber(c gecho.Context) error { - var txReq TransactionRequest - if err := c.Bind(&txReq); err != nil { - log.Error("invalid request params", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) - } - conn, err := grpc.Dial(s.Cfg.RetrieverSocket, grpc.WithInsecure()) - if err != nil { - return c.JSON(http.StatusBadRequest, errors.New("disperser Cannot connect to")) - } - defer conn.Close() - client := pb.NewDataRetrievalClient(conn) - - opt := grpc.MaxCallRecvMsgSize(1024 * 1024 * 300) - request := &pb.FramesAndDataRequest{ - DataStoreId: txReq.StoreNumber, - } - reply, err := client.RetrieveFramesAndData(s.Ctx, request, opt) - if err != nil { - log.Error("RetrieveFramesAndData retrieve frames and data error", "err", err) - return c.JSON(http.StatusBadRequest, errors.New("RetrieveFramesAndData error")) - } - data := reply.GetData() - if len(data) >= 31*s.Cfg.EigenLayerNode { - batchTxn := new([]eigenda.BatchTx) - batchRlpStream := rlp.NewStream(bytes.NewBuffer(data), uint64(len(data))) - err = batchRlpStream.Decode(batchTxn) - if err != nil { - return c.JSON(http.StatusBadRequest, errors.New("decode data fail")) - } - var TxnRep []*TransactionListResponse - newBatchTxn := *batchTxn - for i := 0; i < len(newBatchTxn); i++ { - l2Tx := new(types.Transaction) - rlpStream := l2rlp.NewStream(bytes.NewBuffer(newBatchTxn[i].RawTx), 0) - if err := l2Tx.DecodeRLP(rlpStream); err != nil { - log.Error("Decode RLP fail") - return c.JSON(http.StatusBadRequest, errors.New("Decode RLP fail")) - } - newBlockNumber := new(big.Int).SetBytes(newBatchTxn[i].BlockNumber) - txSl := &TransactionListResponse{ - BlockNumber: newBlockNumber.String(), - TxHash: l2Tx.Hash().String(), - } - TxnRep = append(TxnRep, txSl) - } - return c.JSON(http.StatusOK, TxnRep) - } else { - return c.JSON(http.StatusBadRequest, errors.New("retrieve data is empty, please check da data batch")) - } + //var txReq TransactionRequest + //if err := c.Bind(&txReq); err != nil { + // log.Error("invalid request params", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("invalid request params")) + //} + //conn, err := grpc.Dial(s.Cfg.RetrieverSocket, grpc.WithInsecure()) + //if err != nil { + // return c.JSON(http.StatusBadRequest, errors.New("disperser Cannot connect to")) + //} + //defer conn.Close() + //client := pb.NewDataRetrievalClient(conn) + // + //opt := grpc.MaxCallRecvMsgSize(1024 * 1024 * 300) + //request := &pb.FramesAndDataRequest{ + // DataStoreId: txReq.StoreNumber, + //} + //reply, err := client.RetrieveFramesAndData(s.Ctx, request, opt) + //if err != nil { + // log.Error("RetrieveFramesAndData retrieve frames and data error", "err", err) + // return c.JSON(http.StatusBadRequest, errors.New("RetrieveFramesAndData error")) + //} + //data := reply.GetData() + //if len(data) >= 31*s.Cfg.EigenLayerNode { + // batchTxn := new([]eigenda.BatchTx) + // batchRlpStream := rlp.NewStream(bytes.NewBuffer(data), uint64(len(data))) + // err = batchRlpStream.Decode(batchTxn) + // if err != nil { + // return c.JSON(http.StatusBadRequest, errors.New("decode data fail")) + // } + // var TxnRep []*TransactionListResponse + // newBatchTxn := *batchTxn + // for i := 0; i < len(newBatchTxn); i++ { + // l2Tx := new(types.Transaction) + // rlpStream := l2rlp.NewStream(bytes.NewBuffer(newBatchTxn[i].RawTx), 0) + // if err := l2Tx.DecodeRLP(rlpStream); err != nil { + // log.Error("Decode RLP fail") + // return c.JSON(http.StatusBadRequest, errors.New("Decode RLP fail")) + // } + // newBlockNumber := new(big.Int).SetBytes(newBatchTxn[i].BlockNumber) + // txSl := &TransactionListResponse{ + // BlockNumber: newBlockNumber.String(), + // TxHash: l2Tx.Hash().String(), + // } + // TxnRep = append(TxnRep, txSl) + // } + // return c.JSON(http.StatusOK, TxnRep) + //} else { + // return c.JSON(http.StatusBadRequest, errors.New("retrieve data is empty, please check da data batch")) + //} + return nil } diff --git a/mt-batcher/services/restorer/service.go b/mt-batcher/services/restorer/service.go index 7ac1fb650..8017349f4 100644 --- a/mt-batcher/services/restorer/service.go +++ b/mt-batcher/services/restorer/service.go @@ -5,7 +5,6 @@ import ( "strconv" "sync" - "github.com/Layr-Labs/datalayr/common/graphView" "github.com/ethereum/go-ethereum/log" gecho "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" @@ -24,9 +23,9 @@ type DaServiceConfig struct { } type DaService struct { - Ctx context.Context - Cfg *DaServiceConfig - GraphClient *graphView.GraphClient + Ctx context.Context + Cfg *DaServiceConfig + // GraphClient *graphView.GraphClient GraphqlClient *graphql.Client echo *gecho.Echo cancel func() @@ -42,12 +41,12 @@ func NewDaService(ctx context.Context, cfg *DaServiceConfig) (*DaService, error) })) e.Debug = true e.Use(middleware.Recover()) - graphClient := graphView.NewGraphClient(cfg.GraphProvider, nil) + // graphClient := graphView.NewGraphClient(cfg.GraphProvider, nil) graphqlClient := graphql.NewClient(graphClient.GetEndpoint(), nil) server := &DaService{ - Ctx: ctx, - Cfg: cfg, - GraphClient: graphClient, + Ctx: ctx, + Cfg: cfg, + // GraphClient: graphClient, GraphqlClient: graphqlClient, echo: e, cancel: cancel, diff --git a/mt-batcher/services/sequencer/driver.go b/mt-batcher/services/sequencer/driver.go index 52b2997fd..cfd34afce 100644 --- a/mt-batcher/services/sequencer/driver.go +++ b/mt-batcher/services/sequencer/driver.go @@ -11,20 +11,13 @@ import ( "sync" "time" - "github.com/pkg/errors" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - - "github.com/Layr-Labs/datalayr/common/graphView" - pb "github.com/Layr-Labs/datalayr/common/interfaces/interfaceDL" - "github.com/Layr-Labs/datalayr/common/logging" - "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/ethclient" "github.com/ethereum/go-ethereum/log" + "github.com/pkg/errors" l2gethcommon "github.com/mantlenetworkio/mantle/l2geth/common" l2ethclient "github.com/mantlenetworkio/mantle/l2geth/ethclient" @@ -47,15 +40,15 @@ var ( type SignerFn func(context.Context, common.Address, *types.Transaction) (*types.Transaction, error) type DriverConfig struct { - L1Client *ethclient.Client - L2Client *l2ethclient.Client - L1ChainID *big.Int - DtlClientUrl string - EigenDaContract *bindings.BVMEigenDataLayrChain - RawEigenContract *bind.BoundContract - EigenFeeContract *bindings.BVMEigenDataLayrFee - RawEigenFeeContract *bind.BoundContract - Logger *logging.Logger + L1Client *ethclient.Client + L2Client *l2ethclient.Client + L1ChainID *big.Int + DtlClientUrl string + EigenDaContract *bindings.BVMEigenDataLayrChain + RawEigenContract *bind.BoundContract + EigenFeeContract *bindings.BVMEigenDataLayrFee + RawEigenFeeContract *bind.BoundContract + // Logger *logging.Logger PrivKey *ecdsa.PrivateKey FeePrivKey *ecdsa.PrivateKey BlockOffset uint64 @@ -70,7 +63,7 @@ type DriverConfig struct { CheckerWorkerPollInterval time.Duration GraphPollingDuration time.Duration GraphProvider string - EigenLogConfig logging.Config + // EigenLogConfig logging.Config ResubmissionTimeout time.Duration NumConfirmations uint64 SafeAbortNonceTooLowCount uint64 @@ -102,13 +95,13 @@ type Driver struct { Cfg *DriverConfig WalletAddr common.Address FeeWalletAddr common.Address - GraphClient *graphView.GraphClient - DtlClient client.DtlClient - txMgr txmgr.TxManager - LevelDBStore *db.Store - FeeCh chan *FeePipline - cancel func() - wg sync.WaitGroup + // GraphClient *graphView.GraphClient + DtlClient client.DtlClient + txMgr txmgr.TxManager + LevelDBStore *db.Store + FeeCh chan *FeePipline + cancel func() + wg sync.WaitGroup } var bigOne = new(big.Int).SetUint64(1) @@ -125,7 +118,7 @@ func NewDriver(ctx context.Context, cfg *DriverConfig) (*Driver, error) { txMgr := txmgr.NewSimpleTxManager(txManagerConfig, cfg.L1Client) - graphClient := graphView.NewGraphClient(cfg.GraphProvider, cfg.Logger) + // graphClient := graphView.NewGraphClient(cfg.GraphProvider, cfg.Logger) levelDBStore, err := db.NewStore(cfg.DbPath) if err != nil { @@ -146,12 +139,12 @@ func NewDriver(ctx context.Context, cfg *DriverConfig) (*Driver, error) { Ctx: ctx, WalletAddr: walletAddr, FeeWalletAddr: feeWalletAddr, - GraphClient: graphClient, - DtlClient: dtlClient, - txMgr: txMgr, - LevelDBStore: levelDBStore, - FeeCh: make(chan *FeePipline), - cancel: cancel, + // GraphClient: graphClient, + DtlClient: dtlClient, + txMgr: txMgr, + LevelDBStore: levelDBStore, + FeeCh: make(chan *FeePipline), + cancel: cancel, }, nil } @@ -528,79 +521,81 @@ func (d *Driver) ConfirmStoredData(txHash []byte, params common2.StoreParams, st } func (d *Driver) callEncode(data []byte) (common2.StoreParams, error) { - conn, err := grpc.Dial(d.Cfg.DisperserSocket, grpc.WithTransportCredentials(insecure.NewCredentials())) - if err != nil { - log.Error("MtBatcher Disperser Cannot connect to", "DisperserSocket", d.Cfg.DisperserSocket) - return common2.StoreParams{}, err - } - defer conn.Close() - c := pb.NewDataDispersalClient(conn) - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Cfg.DataStoreTimeout)) - defer cancel() - request := &pb.EncodeStoreRequest{ - Duration: d.Cfg.DataStoreDuration, - Data: data, - } - opt := grpc.MaxCallSendMsgSize(1024 * 1024 * 300) - reply, err := c.EncodeStore(ctx, request, opt) - if err != nil { - log.Error("MtBatcher get store err", err) - return common2.StoreParams{}, err - } - g := reply.GetStore() - feeBigInt := new(big.Int).SetBytes(g.Fee) - params := common2.StoreParams{ - ReferenceBlockNumber: g.ReferenceBlockNumber, - TotalOperatorsIndex: g.TotalOperatorsIndex, - OrigDataSize: g.OrigDataSize, - NumTotal: g.NumTotal, - Quorum: g.Quorum, - NumSys: g.NumSys, - NumPar: g.NumPar, - Duration: g.Duration, - KzgCommit: g.KzgCommit, - LowDegreeProof: g.LowDegreeProof, - Degree: g.Degree, - TotalSize: g.TotalSize, - Order: g.Order, - Fee: feeBigInt, - HeaderHash: g.HeaderHash, - Disperser: g.Disperser, - } - return params, nil + //conn, err := grpc.Dial(d.Cfg.DisperserSocket, grpc.WithTransportCredentials(insecure.NewCredentials())) + //if err != nil { + // log.Error("MtBatcher Disperser Cannot connect to", "DisperserSocket", d.Cfg.DisperserSocket) + // return common2.StoreParams{}, err + //} + //defer conn.Close() + //c := pb.NewDataDispersalClient(conn) + //ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Cfg.DataStoreTimeout)) + //defer cancel() + //request := &pb.EncodeStoreRequest{ + // Duration: d.Cfg.DataStoreDuration, + // Data: data, + //} + //opt := grpc.MaxCallSendMsgSize(1024 * 1024 * 300) + //reply, err := c.EncodeStore(ctx, request, opt) + //if err != nil { + // log.Error("MtBatcher get store err", err) + // return common2.StoreParams{}, err + //} + //g := reply.GetStore() + //feeBigInt := new(big.Int).SetBytes(g.Fee) + //params := common2.StoreParams{ + // ReferenceBlockNumber: g.ReferenceBlockNumber, + // TotalOperatorsIndex: g.TotalOperatorsIndex, + // OrigDataSize: g.OrigDataSize, + // NumTotal: g.NumTotal, + // Quorum: g.Quorum, + // NumSys: g.NumSys, + // NumPar: g.NumPar, + // Duration: g.Duration, + // KzgCommit: g.KzgCommit, + // LowDegreeProof: g.LowDegreeProof, + // Degree: g.Degree, + // TotalSize: g.TotalSize, + // Order: g.Order, + // Fee: feeBigInt, + // HeaderHash: g.HeaderHash, + // Disperser: g.Disperser, + //} + //return params, nil + return common2.StoreParams{}, nil } func (d *Driver) callDisperse(headerHash []byte, messageHash []byte) (common2.DisperseMeta, error) { - conn, err := grpc.Dial(d.Cfg.DisperserSocket, grpc.WithInsecure()) - if err != nil { - log.Error("MtBatcher Dial DisperserSocket", "err", err) - return common2.DisperseMeta{}, err - } - defer conn.Close() - c := pb.NewDataDispersalClient(conn) - ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Cfg.DataStoreTimeout)) - defer cancel() - request := &pb.DisperseStoreRequest{ - HeaderHash: headerHash, - MessageHash: messageHash, - } - reply, err := c.DisperseStore(ctx, request) - if err != nil { - return common2.DisperseMeta{}, err - } - sigs := reply.GetSigs() - aggSig := common2.AggregateSignature{ - AggSig: sigs.AggSig, - StoredAggPubkeyG1: sigs.StoredAggPubkeyG1, - UsedAggPubkeyG2: sigs.UsedAggPubkeyG2, - NonSignerPubkeys: sigs.NonSignerPubkeys, - } - meta := common2.DisperseMeta{ - Sigs: aggSig, - ApkIndex: reply.GetApkIndex(), - TotalStakeIndex: reply.GetTotalStakeIndex(), - } - return meta, nil + //conn, err := grpc.Dial(d.Cfg.DisperserSocket, grpc.WithInsecure()) + //if err != nil { + // log.Error("MtBatcher Dial DisperserSocket", "err", err) + // return common2.DisperseMeta{}, err + //} + //defer conn.Close() + //c := pb.NewDataDispersalClient(conn) + //ctx, cancel := context.WithTimeout(context.Background(), time.Duration(d.Cfg.DataStoreTimeout)) + //defer cancel() + //request := &pb.DisperseStoreRequest{ + // HeaderHash: headerHash, + // MessageHash: messageHash, + //} + //reply, err := c.DisperseStore(ctx, request) + //if err != nil { + // return common2.DisperseMeta{}, err + //} + //sigs := reply.GetSigs() + //aggSig := common2.AggregateSignature{ + // AggSig: sigs.AggSig, + // StoredAggPubkeyG1: sigs.StoredAggPubkeyG1, + // UsedAggPubkeyG2: sigs.UsedAggPubkeyG2, + // NonSignerPubkeys: sigs.NonSignerPubkeys, + //} + //meta := common2.DisperseMeta{ + // Sigs: aggSig, + // ApkIndex: reply.GetApkIndex(), + // TotalStakeIndex: reply.GetTotalStakeIndex(), + //} + //return meta, nil + return common2.DisperseMeta{}, nil } func (d *Driver) CalcUserFeeByRules(rollupDateSize *big.Int) (*big.Int, error) { diff --git a/mt-challenger/challenger/challenger.go b/mt-challenger/challenger/challenger.go index 369f91417..c69847823 100644 --- a/mt-challenger/challenger/challenger.go +++ b/mt-challenger/challenger/challenger.go @@ -1,794 +1,795 @@ package challenger -import ( - "bytes" - "context" - "crypto/ecdsa" - "encoding/hex" - "fmt" - "math/big" - "strconv" - "strings" - "sync" - "time" - - "github.com/pkg/errors" - "github.com/shurcooL/graphql" - "google.golang.org/grpc" - - datalayr "github.com/Layr-Labs/datalayr/common/contracts" - gkzg "github.com/Layr-Labs/datalayr/common/crypto/go-kzg-bn254" - "github.com/Layr-Labs/datalayr/common/graphView" - "github.com/Layr-Labs/datalayr/common/header" - pb "github.com/Layr-Labs/datalayr/common/interfaces/interfaceRetrieverServer" - "github.com/Layr-Labs/datalayr/common/logging" - - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - ethc "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/log" - "github.com/ethereum/go-ethereum/rlp" - - "github.com/mantlenetworkio/mantle/l2geth/common" - l2types "github.com/mantlenetworkio/mantle/l2geth/core/types" - l2ethclient "github.com/mantlenetworkio/mantle/l2geth/ethclient" - l2rlp "github.com/mantlenetworkio/mantle/l2geth/rlp" - "github.com/mantlenetworkio/mantle/l2geth/rollup/eigenda" - common4 "github.com/mantlenetworkio/mantle/mt-batcher/services/common" - "github.com/mantlenetworkio/mantle/mt-batcher/txmgr" - "github.com/mantlenetworkio/mantle/mt-challenger/bindings" - rc "github.com/mantlenetworkio/mantle/mt-challenger/bindings" - "github.com/mantlenetworkio/mantle/mt-challenger/challenger/client" - "github.com/mantlenetworkio/mantle/mt-challenger/challenger/db" - "github.com/mantlenetworkio/mantle/mt-challenger/metrics" -) - -const fraudString = "2d5f2860204f2060295f2d202d5f2860206f2060295f2d202d5f286020512060295f2d2042495444414f204a5553542052454b5420594f55207c5f2860204f2060295f7c202d207c5f2860206f2060295f7c202d207c5f286020512060295f7c" - -type SignerFn func(context.Context, ethc.Address, *types.Transaction) (*types.Transaction, error) - -var ( - errMaxPriorityFeePerGasNotFound = errors.New( - "Method eth_maxPriorityFeePerGas not found", - ) - FallbackGasTipCap = big.NewInt(1500000000) -) - -var totalDaNode int - -type KzgConfig struct { - G1Path string - G2Path string - TableDir string - NumWorker int - Order uint64 // Order is the total size of SRS -} - -type Fraud struct { - StartingIndex int -} - -type DataLayrDisclosureProof struct { - Header []byte - Polys [][]byte - MultirevealProofs []datalayr.MultiRevealProof - BatchPolyEquivalenceProof [4]*big.Int - StartingChunkIndex int -} - -type FraudProof struct { - DataLayrDisclosureProof - StartingSymbolIndex int -} - -type ChallengerConfig struct { - L1Client *ethclient.Client - L2Client *l2ethclient.Client - L1ChainID *big.Int - EigenContractAddr ethc.Address - Logger *logging.Logger - PrivKey *ecdsa.PrivateKey - GraphProvider string - RetrieverSocket string - DtlClientUrl string - KzgConfig KzgConfig - LastStoreNumber uint64 - Timeout time.Duration - PollInterval time.Duration - CompensatePollInterval time.Duration - DbPath string - CheckerBatchIndex uint64 - UpdateBatchIndexStep uint64 - NeedReRollupBatch string - ChallengerCheckEnable bool - ReRollupToolEnable bool - DataCompensateEnable bool - SignerFn SignerFn - ResubmissionTimeout time.Duration - NumConfirmations uint64 - SafeAbortNonceTooLowCount uint64 - Metrics metrics.ChallengerMetrics - - EnableHsm bool - HsmAPIName string - HsmCreden string - HsmAddress string -} - -type Challenger struct { - Ctx context.Context - Cfg *ChallengerConfig - EigenDaContract *bindings.BVMEigenDataLayrChain - RawEigenContract *bind.BoundContract - WalletAddr ethc.Address - EigenABI *abi.ABI - GraphClient *graphView.GraphClient - GraphqlClient *graphql.Client - DtlEigenClient client.DtlClient - LevelDBStore *db.Store - txMgr txmgr.TxManager - cancel func() - wg sync.WaitGroup - once sync.Once -} - -func NewChallenger(ctx context.Context, cfg *ChallengerConfig) (*Challenger, error) { - _, cancel := context.WithTimeout(ctx, common4.DefaultTimeout) - defer cancel() - eigenContract, err := bindings.NewBVMEigenDataLayrChain( - ethc.Address(cfg.EigenContractAddr), cfg.L1Client, - ) - if err != nil { - return nil, err - } - parsed, err := abi.JSON(strings.NewReader( - bindings.BVMEigenDataLayrChainABI, - )) - if err != nil { - log.Error("MtChallenger parse eigen layer contract abi fail", "err", err) - return nil, err - } - eignenABI, err := bindings.BVMEigenDataLayrChainMetaData.GetAbi() - if err != nil { - log.Error("MtChallenger get eigen layer contract abi fail", "err", err) - return nil, err - } - rawEigenContract := bind.NewBoundContract( - cfg.EigenContractAddr, parsed, cfg.L1Client, cfg.L1Client, - cfg.L1Client, - ) - - txManagerConfig := txmgr.Config{ - ResubmissionTimeout: cfg.ResubmissionTimeout, - ReceiptQueryInterval: time.Second, - NumConfirmations: cfg.NumConfirmations, - SafeAbortNonceTooLowCount: cfg.SafeAbortNonceTooLowCount, - } - - txMgr := txmgr.NewSimpleTxManager(txManagerConfig, cfg.L1Client) - - graphClient := graphView.NewGraphClient(cfg.GraphProvider, cfg.Logger) - graphqlClient := graphql.NewClient(graphClient.GetEndpoint(), nil) - var walletAddr ethc.Address - if cfg.EnableHsm { - walletAddr = ethc.HexToAddress(cfg.HsmAddress) - } else { - walletAddr = crypto.PubkeyToAddress(cfg.PrivKey.PublicKey) - } - - levelDBStore, err := db.NewStore(cfg.DbPath) - if err != nil { - log.Error("MtChallenger init leveldb fail", "err", err) - return nil, err - } - dtlEigenClient := client.NewDtlClient(cfg.DtlClientUrl) - if dtlEigenClient == nil { - return nil, fmt.Errorf("MtChallenger new eigen client fail") - } - return &Challenger{ - Cfg: cfg, - Ctx: ctx, - EigenDaContract: eigenContract, - RawEigenContract: rawEigenContract, - WalletAddr: walletAddr, - EigenABI: eignenABI, - GraphClient: graphClient, - GraphqlClient: graphqlClient, - DtlEigenClient: dtlEigenClient, - LevelDBStore: levelDBStore, - txMgr: txMgr, - cancel: cancel, - }, nil -} - -func (c *Challenger) getDataStoreById(dataStoreId string) (*graphView.DataStore, error) { - var query struct { - DataStore graphView.DataStoreGql `graphql:"dataStore(id: $storeId)"` - } - variables := map[string]interface{}{ - "storeId": graphql.String(dataStoreId), - } - err := c.GraphqlClient.Query(context.Background(), &query, variables) - if err != nil { - log.Error("MtChallenger query data from graphql fail", "err", err) - return nil, err - } - store, err := query.DataStore.Convert() - if err != nil { - log.Error("MtChallenger convert data store fail", "err", err) - return nil, err - } - c.Cfg.LastStoreNumber = uint64(store.StoreNumber) - return store, nil -} - -func (c *Challenger) callRetrieve(store *graphView.DataStore) ([]byte, []datalayr.Frame, error) { - conn, err := grpc.Dial(c.Cfg.RetrieverSocket, grpc.WithInsecure()) - if err != nil { - log.Error("MtChallenger disperser Cannot connect to", "retriever-socket", c.Cfg.RetrieverSocket, "err", err) - return nil, nil, err - } - defer conn.Close() - client := pb.NewDataRetrievalClient(conn) - ctx, cancel := context.WithTimeout(context.Background(), c.Cfg.Timeout) - defer cancel() - opt := grpc.MaxCallRecvMsgSize(1024 * 1024 * 300) - request := &pb.FramesAndDataRequest{ - DataStoreId: store.StoreNumber, - } - reply, err := client.RetrieveFramesAndData(ctx, request, opt) - if err != nil { - return nil, nil, err - } - data := reply.GetData() - framesBytes := reply.GetFrames() - header, err := header.DecodeDataStoreHeader(store.Header) - if err != nil { - log.Error("MtChallenger Could not decode header", "err", err) - return nil, nil, err - } - frames := make([]datalayr.Frame, header.NumSys+header.NumPar) - for i, frameBytes := range framesBytes { - frame, err := datalayr.DecodeFrame(frameBytes) - if err == nil { - frames[i] = frame - } else { - return nil, nil, errors.New("MtChallenger Does not Contain all the frames") - } - } - return data, frames, nil -} - -// check if the fraud string exists within the data -func (c *Challenger) checkForFraud(store *graphView.DataStore, data []byte) (*Fraud, bool) { - dataString := hex.EncodeToString(data) - index := strings.Index(dataString, fraudString) - if index != -1 { - return &Fraud{StartingIndex: index / 2}, true - } - return nil, false -} - -func (c *Challenger) constructFraudProof(store *graphView.DataStore, data []byte, fraud *Fraud, frames []datalayr.Frame) (*FraudProof, error) { - // encode data to frames here - header, err := header.DecodeDataStoreHeader(store.Header) - if err != nil { - c.Cfg.Logger.Printf("MtChallenger Could not decode header %v. %v\n", header, err) - return nil, err - } - config := c.Cfg.KzgConfig - - s1 := gkzg.ReadG1Points(config.G1Path, config.Order, config.NumWorker) - s2 := gkzg.ReadG2Points(config.G2Path, config.Order, config.NumWorker) - - dp := datalayr.NewDisclosureProver(s1, s2) - - //there are 31 bytes per fr so there are 31*chunkLenE bytes in each chunk - //so the i'th byte starts at the (i/(31*encoder.EncodingParams.ChunkLenE))'th chunk - startingChunkIndex := fraud.StartingIndex / int(31*header.Degree) - //the fraud string ends len(fraudString)/2 bytes later - endingChunkIndex := (fraud.StartingIndex + len(fraudString)/2) / int(31*header.Degree) - startingSymbolIndex := fraud.StartingIndex % int(31*header.Degree) - //do some math to shift this over by the correct number of bytes - //there are 32 bytes in the actual poly for every 31 bytes in the data, hence (startingSymbolIndex/31)*32 - //then we shift over by 1 to get past the first 0 byte, and then (startingSymbolIndex % 31) - startingSymbolIndex = (startingSymbolIndex/31)*32 + 1 + (startingSymbolIndex % 31) - - //check frames range - if startingChunkIndex > len(frames) { - return nil, fmt.Errorf("startingChunkIndex is out of frames range, startingChunkIndex: %d, len(frames): %d", startingChunkIndex, len(frames)) - } - - //generate parameters for proving data on chain - //this is - // polys: the []byte representation of the polynomials - // multirevealProofs: the openings of each polynomial against the full polynomial commitment - // batchPolyEquivalenceProof: the proof that the `polys` are in fact represented by the commitments in `multirevealProofs` - polys, multirevealProofs, batchPolyEquivalenceProof, err := dp.ProveBatchInterpolatingPolyDisclosure(frames[startingChunkIndex:endingChunkIndex+1], store.DataCommitment, store.Header, uint32(startingChunkIndex)) - if err != nil { - return nil, err - } - - disclosureProof := DataLayrDisclosureProof{ - Header: store.Header, - Polys: polys, - MultirevealProofs: multirevealProofs, - BatchPolyEquivalenceProof: batchPolyEquivalenceProof, - StartingChunkIndex: startingChunkIndex, - } - - return &FraudProof{DataLayrDisclosureProof: disclosureProof, StartingSymbolIndex: startingSymbolIndex}, nil -} - -func (fp *DataLayrDisclosureProof) ToDisclosureProofs() rc.BVMEigenDataLayrChainDisclosureProofs { - proofs := make([]rc.DataLayrDisclosureLogicMultiRevealProof, 0) - for _, oldProof := range fp.MultirevealProofs { - newProof := rc.DataLayrDisclosureLogicMultiRevealProof{ - InterpolationPoly: rc.BN254G1Point{X: oldProof.InterpolationPolyCommit[0], Y: oldProof.InterpolationPolyCommit[1]}, - RevealProof: rc.BN254G1Point{X: oldProof.RevealProof[0], Y: oldProof.RevealProof[1]}, - ZeroPoly: rc.BN254G2Point{ - //preserve this ordering for dumb precompile reasons - X: [2]*big.Int{oldProof.ZeroPolyCommit[1], oldProof.ZeroPolyCommit[0]}, - Y: [2]*big.Int{oldProof.ZeroPolyCommit[3], oldProof.ZeroPolyCommit[2]}, - }, - ZeroPolyProof: oldProof.ZeroPolyProof, - } - proofs = append(proofs, newProof) - } - return rc.BVMEigenDataLayrChainDisclosureProofs{ - Header: fp.Header, - FirstChunkNumber: uint32(fp.StartingChunkIndex), - Polys: fp.Polys, - MultiRevealProofs: proofs, - PolyEquivalenceProof: rc.BN254G2Point{ - //preserve this ordering for dumb precompile reasons - X: [2]*big.Int{fp.BatchPolyEquivalenceProof[1], fp.BatchPolyEquivalenceProof[0]}, - Y: [2]*big.Int{fp.BatchPolyEquivalenceProof[3], fp.BatchPolyEquivalenceProof[2]}, - }, - } -} - -func (c *Challenger) UpdateGasPrice(ctx context.Context, tx *types.Transaction) (*types.Transaction, error) { - var opts *bind.TransactOpts - var err error - if !c.Cfg.EnableHsm { - opts, err = bind.NewKeyedTransactorWithChainID( - c.Cfg.PrivKey, c.Cfg.L1ChainID, - ) - } else { - opts, err = common4.NewHSMTransactOpts(ctx, c.Cfg.HsmAPIName, - c.Cfg.HsmAddress, c.Cfg.L1ChainID, c.Cfg.HsmCreden) - } - if err != nil { - return nil, err - } - opts.Context = ctx - opts.Nonce = new(big.Int).SetUint64(tx.Nonce()) - opts.NoSend = true - - finalTx, err := c.RawEigenContract.RawTransact(opts, tx.Data()) - switch { - case err == nil: - return finalTx, nil - - case c.IsMaxPriorityFeePerGasNotFoundError(err): - log.Info("MtChallenger eth_maxPriorityFeePerGas is unsupported by current backend, using fallback gasTipCap", "txData", tx.Data()) - opts.GasTipCap = FallbackGasTipCap - return c.RawEigenContract.RawTransact(opts, tx.Data()) - - default: - return nil, err - } -} - -func (c *Challenger) SendTransaction(ctx context.Context, tx *types.Transaction) error { - return c.Cfg.L1Client.SendTransaction(ctx, tx) -} - -func (c *Challenger) IsMaxPriorityFeePerGasNotFoundError(err error) bool { - return strings.Contains( - err.Error(), errMaxPriorityFeePerGasNotFound.Error(), - ) -} - -func (c *Challenger) ChallengeProveFraud(ctx context.Context, fraudStoreNumber *big.Int, fraudProof *FraudProof, searchData rc.IDataLayrServiceManagerDataStoreSearchData, disclosureProofs rc.BVMEigenDataLayrChainDisclosureProofs) (*types.Transaction, error) { - balance, err := c.Cfg.L1Client.BalanceAt( - c.Ctx, ethc.Address(c.WalletAddr), nil, - ) - if err != nil { - log.Error("MtChallenger unable to get current balance", "err", err) - return nil, err - } - log.Info("MtChallenger wallet address balance", "balance", balance) - nonce64, err := c.Cfg.L1Client.NonceAt( - c.Ctx, ethc.Address(c.WalletAddr), nil, - ) - if err != nil { - log.Error("MtChallenger unable to get current nonce", "err", err) - return nil, err - } - nonce := new(big.Int).SetUint64(nonce64) - var opts *bind.TransactOpts - if !c.Cfg.EnableHsm { - opts, err = bind.NewKeyedTransactorWithChainID( - c.Cfg.PrivKey, c.Cfg.L1ChainID, - ) - } else { - opts, err = common4.NewHSMTransactOpts(ctx, c.Cfg.HsmAPIName, - c.Cfg.HsmAddress, c.Cfg.L1ChainID, c.Cfg.HsmCreden) - } - if err != nil { - return nil, err - } - opts.Context = ctx - opts.Nonce = nonce - opts.NoSend = true - tx, err := c.EigenDaContract.ProveFraud(opts, fraudStoreNumber, new(big.Int).SetUint64(uint64(fraudProof.StartingSymbolIndex)), searchData, disclosureProofs) - switch { - case err == nil: - return tx, nil - - case c.IsMaxPriorityFeePerGasNotFoundError(err): - log.Warn("MtChallenger eth_maxPriorityFeePerGas is unsupported by current backend, using fallback gasTipCap") - opts.GasTipCap = FallbackGasTipCap - return c.EigenDaContract.ProveFraud(opts, fraudStoreNumber, new(big.Int).SetUint64(uint64(fraudProof.StartingSymbolIndex)), searchData, disclosureProofs) - - default: - return nil, err - } -} - -func (c *Challenger) postFraudProof(store *graphView.DataStore, fraudProof *FraudProof) (*types.Transaction, error) { - searchData := rc.IDataLayrServiceManagerDataStoreSearchData{ - Duration: store.Duration, - Timestamp: new(big.Int).SetUint64(uint64(store.InitTime)), - Index: store.Index, - Metadata: rc.IDataLayrServiceManagerDataStoreMetadata{ - HeaderHash: store.DataCommitment, - DurationDataStoreId: store.DurationDataStoreId, - GlobalDataStoreId: store.StoreNumber, - BlockNumber: store.ReferenceBlockNumber, - Fee: store.Fee, - Confirmer: ethc.Address(common.HexToAddress(store.Confirmer)), - SignatoryRecordHash: store.SignatoryRecord, - }, - } - disclosureProofs := fraudProof.ToDisclosureProofs() - fraudStoreNumber, err := c.EigenDaContract.DataStoreIdToRollupStoreNumber(&bind.CallOpts{}, store.StoreNumber) - if err != nil { - return nil, err - } - - tx, err := c.ChallengeProveFraud(c.Ctx, fraudStoreNumber, fraudProof, searchData, disclosureProofs) - if err != nil { - return nil, err - } - updateGasPrice := func(ctx context.Context) (*types.Transaction, error) { - log.Info("MtChallenger ConfirmData update gas price") - return c.UpdateGasPrice(ctx, tx) - } - receipt, err := c.txMgr.Send( - c.Ctx, updateGasPrice, c.SendTransaction, - ) - if err != nil { - return nil, err - } - log.Info("MtChallenger challenger prove fraud success", "TxHash", receipt.TxHash) - return tx, nil -} - -func (c *Challenger) makeReRollupBatchTx(ctx context.Context, batchIndex *big.Int) (*types.Transaction, error) { - balance, err := c.Cfg.L1Client.BalanceAt( - c.Ctx, ethc.Address(c.WalletAddr), nil, - ) - if err != nil { - log.Error("MtChallenger unable to get current balance", "err", err) - return nil, err - } - log.Info("MtChallenger wallet address balance", "balance", balance) - c.Cfg.Metrics.BalanceETH().Set(common4.WeiToEth64(balance)) - nonce64, err := c.Cfg.L1Client.NonceAt( - c.Ctx, ethc.Address(c.WalletAddr), nil, - ) - if err != nil { - log.Error("MtChallenger unable to get current nonce", "err", err) - return nil, err - } - c.Cfg.Metrics.NonceETH().Inc() - nonce := new(big.Int).SetUint64(nonce64) - var opts *bind.TransactOpts - if !c.Cfg.EnableHsm { - opts, err = bind.NewKeyedTransactorWithChainID( - c.Cfg.PrivKey, c.Cfg.L1ChainID, - ) - } else { - opts, err = common4.NewHSMTransactOpts(ctx, c.Cfg.HsmAPIName, - c.Cfg.HsmAddress, c.Cfg.L1ChainID, c.Cfg.HsmCreden) - } - if err != nil { - return nil, err - } - opts.Context = ctx - opts.Nonce = nonce - opts.NoSend = true - - tx, err := c.EigenDaContract.SubmitReRollUpInfo(opts, batchIndex) - switch { - case err == nil: - return tx, nil - - case c.IsMaxPriorityFeePerGasNotFoundError(err): - log.Warn("MtChallenger eth_maxPriorityFeePerGas is unsupported by current backend, using fallback gasTipCap") - opts.GasTipCap = FallbackGasTipCap - return c.EigenDaContract.SubmitReRollUpInfo(opts, batchIndex) - default: - return nil, err - } -} - -func (c *Challenger) submitReRollupBatchIndex(batchIndex *big.Int) (*types.Transaction, error) { - tx, err := c.makeReRollupBatchTx(c.Ctx, batchIndex) - if err != nil { - return nil, err - } - updateGasPrice := func(ctx context.Context) (*types.Transaction, error) { - log.Info("MtChallenger makReRollupBatchTx update gas price") - return c.UpdateGasPrice(ctx, tx) - } - receipt, err := c.txMgr.Send( - c.Ctx, updateGasPrice, c.SendTransaction, - ) - if err != nil { - return nil, err - } - log.Info("MtChallenger submit re-rollup batch index success", "TxHash", receipt.TxHash) - return tx, nil -} - -func (c *Challenger) GetEigenLayerNode() (int, error) { - operators, err := c.GraphClient.QueryOperatorsByStatus() - if err != nil { - log.Error("MtChallenger query operators fail", "err", err) - return 0, err - } - return len(operators), nil -} - -func (c *Challenger) ServiceInit() error { - nodeNum, err := c.GetEigenLayerNode() - if err != nil { - log.Error("MtChallenger get batch index fail", "err", err) - return err - } - totalDaNode = nodeNum - walletBalance, err := c.Cfg.L1Client.BalanceAt( - c.Ctx, c.WalletAddr, nil, - ) - if err != nil { - log.Warn("Get rollup wallet address balance fail", "err", err) - return err - } - c.Cfg.Metrics.BalanceETH().Set(common4.WeiToEth64(walletBalance)) - nonce, err := c.Cfg.L1Client.NonceAt( - c.Ctx, c.WalletAddr, nil, - ) - if err != nil { - log.Warn("Get rollup wallet address nonce fail", "err", err) - return err - } - c.Cfg.Metrics.NonceETH().Set(float64(nonce)) - return nil -} - -func (c *Challenger) Start() error { - err := c.ServiceInit() - if err != nil { - log.Error("service init error", "err", err) - return err - } - if c.Cfg.ChallengerCheckEnable { - c.wg.Add(1) - go c.eventLoop() - } - if c.Cfg.DataCompensateEnable { - c.wg.Add(1) - go c.dataCompensateForDlNodeExitsLoop() - } - c.once.Do(func() { - log.Info("MtChallenger start exec once update da tool") - if c.Cfg.ReRollupToolEnable { - reRollupBatchIndex := strings.Split(c.Cfg.NeedReRollupBatch, "|") - for index := 0; index < len(reRollupBatchIndex); index++ { - bigParam := new(big.Int) - bigBatchIndex, ok := bigParam.SetString(reRollupBatchIndex[index], 10) - if !ok { - log.Error("MtChallenger string to big.int fail", "ok", ok) - continue - } - tx, err := c.submitReRollupBatchIndex(bigBatchIndex) - if err != nil { - log.Error("MtChallenger tool submit re-rollup info fail", "batchIndex", reRollupBatchIndex[index], "err", err) - continue - } - c.Cfg.Metrics.ReRollupBatchIndex().Set(float64(bigBatchIndex.Uint64())) - log.Info("MtChallenger tool submit re-rollup info success", "batchIndex", reRollupBatchIndex[index], "txHash", tx.Hash().String()) - updBatchIndex, err := strconv.ParseUint(reRollupBatchIndex[index], 10, 64) - if err != nil { - log.Error("MtChallenger tool type string to uint64 fail") - } - c.LevelDBStore.SetLatestBatchIndex(updBatchIndex) - } - } - }) - return nil -} - -func (c *Challenger) Stop() { - c.cancel() - c.wg.Wait() -} - -func (c *Challenger) eventLoop() { - defer c.wg.Done() - ticker := time.NewTicker(c.Cfg.PollInterval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - latestBatchIndex, err := c.EigenDaContract.RollupBatchIndex(&bind.CallOpts{}) - if err != nil { - log.Error("MtChallenger get batch index fail", "err", err) - continue - } - batchIndex, ok := c.LevelDBStore.GetLatestBatchIndex() - if !ok { - log.Error("MtChallenger get batch index from db fail", "err", err) - continue - } - if c.Cfg.CheckerBatchIndex > latestBatchIndex.Uint64() { - log.Info("MtChallenger Batch Index", "DbBatchIndex", batchIndex, "ContractBatchIndex", latestBatchIndex.Uint64()-c.Cfg.CheckerBatchIndex) - continue - } - if batchIndex >= (latestBatchIndex.Uint64() - c.Cfg.CheckerBatchIndex) { - log.Info("MtChallenger db batch index and contract batch idnex is equal", "DbBatchIndex", batchIndex, "ContractBatchIndex", latestBatchIndex.Uint64()-c.Cfg.CheckerBatchIndex) - continue - } - log.Info("MtChallenger db batch index and contract batch idnex", - "DbBatchIndex", batchIndex, "ContractBatchIndex", latestBatchIndex.Uint64(), - "latestBatchIndex.Uint64() - c.Cfg.CheckerBatchIndex", latestBatchIndex.Uint64()-c.Cfg.CheckerBatchIndex, - ) - c.Cfg.Metrics.CheckBatchIndex().Set(float64(latestBatchIndex.Uint64() - c.Cfg.CheckerBatchIndex)) - for i := batchIndex; i <= (latestBatchIndex.Uint64() - c.Cfg.CheckerBatchIndex); i++ { - dataStoreId, err := c.EigenDaContract.GetRollupStoreByRollupBatchIndex(&bind.CallOpts{}, big.NewInt(int64(i))) - if err != nil { - continue - } - if dataStoreId.DataStoreId == 0 { - log.Info("MtChallenger get rollup store id", "DataStoreId", dataStoreId.DataStoreId) - continue - } - store, err := c.getDataStoreById(strconv.Itoa(int(dataStoreId.DataStoreId))) - if err != nil { - log.Error("MtChallenger get data store fail", "err", err) - continue - } - log.Info("MtChallenger get data store by id success", "Confirmed", store.Confirmed) - if store.Confirmed { - data, frames, err := c.callRetrieve(store) - if err != nil { - log.Error("MtChallenger error getting data", "err", err) - continue - } - batchTxn := new([]eigenda.BatchTx) - batchRlpStream := rlp.NewStream(bytes.NewBuffer(data), uint64(len(data))) - err = batchRlpStream.Decode(batchTxn) - if err != nil { - log.Error("MtChallenger decode batch txn fail", "err", err) - continue - } - newBatchTxn := *batchTxn - for i := 0; i < len(newBatchTxn); i++ { - l2Tx := new(l2types.Transaction) - rlpStream := l2rlp.NewStream(bytes.NewBuffer(newBatchTxn[i].RawTx), 0) - if err := l2Tx.DecodeRLP(rlpStream); err != nil { - c.Cfg.Logger.Error().Err(err).Msg("Decode RLP fail") - } - - // tx check for tmp, will remove in future - l2Transaction, _, err := c.Cfg.L2Client.TransactionByHash(c.Ctx, l2Tx.Hash()) - if err != nil { - log.Error("MtChallenger no this transaction", "err", err) - continue - } - log.Info("MtChallenger fond transaction", "hash", l2Transaction.Hash().Hex()) - } - - // check if the fraud string exists within the data - fraud, exists := c.checkForFraud(store, data) - if !exists { - log.Info("MtChallenger no fraud") - c.LevelDBStore.SetLatestBatchIndex(i) - continue - } - proof, err := c.constructFraudProof(store, data, fraud, frames) - if err != nil { - log.Error("MtChallenger error constructing fraud", "err", err) - continue - } - tx, err := c.postFraudProof(store, proof) - if err != nil { - log.Error("MtChallenger error posting fraud proof", "err", err) - continue - } - log.Info("MtChallenger fraud proof tx", "hash", tx.Hash().Hex()) - } - c.LevelDBStore.SetLatestBatchIndex(i) - } - case err := <-c.Ctx.Done(): - log.Error("MtChallenger eigenDa sequencer service shutting down", "err", err) - return - } - } -} - -func (c *Challenger) dataCompensateForDlNodeExitsLoop() { - defer c.wg.Done() - ticker := time.NewTicker(c.Cfg.CompensatePollInterval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - nodeNum, err := c.GetEigenLayerNode() - if err != nil { - log.Error("MtChallenger data compensate get da node", "err", err) - continue - } - if nodeNum == totalDaNode { - log.Info("MtChallenger current da node and history da node", "current", nodeNum, "history", totalDaNode) - continue - } else { - // get dtl latest batch index sync from da retriver - dtlBatchIndex, batchErr := c.DtlEigenClient.GetLatestTransactionBatchIndex() - if err != nil { - log.Error("MtChallenger get latest batch index fail", "dtlBatchIndex", dtlBatchIndex, "batchErr", batchErr) - continue - } - contractBatchIndex, batchContractErr := c.EigenDaContract.RollupBatchIndex(&bind.CallOpts{}) - if err != nil { - log.Error("MtChallenger get latest batch from contract fail", "contractBatchIndex", contractBatchIndex, "batchErr", batchContractErr) - continue - } - if dtlBatchIndex != 0 { - var updateEndBatchIndex uint64 - if dtlBatchIndex+c.Cfg.UpdateBatchIndexStep > contractBatchIndex.Uint64() { - updateEndBatchIndex = dtlBatchIndex + c.Cfg.UpdateBatchIndexStep - } else { - updateEndBatchIndex = contractBatchIndex.Uint64() - } - for batchIndex := dtlBatchIndex; batchIndex <= updateEndBatchIndex; batchIndex++ { - bigParam := new(big.Int) - bigBatchIndex, ok := bigParam.SetString(strconv.FormatUint(batchIndex, 10), 10) - if !ok { - log.Error("MtChallenger string to big.int fail", "ok", ok) - continue - } - tx, err := c.submitReRollupBatchIndex(bigBatchIndex) - if err != nil { - log.Error("MtChallenger data compensate submit re-rollup info fail", "batchIndex", bigBatchIndex, "err", err) - continue - } - c.Cfg.Metrics.ReRollupBatchIndex().Set(float64(bigBatchIndex.Uint64())) - log.Info("MtChallenger tool submit re-rollup info success", "batchIndex", bigBatchIndex, "txHash", tx.Hash().String()) - } - } - totalDaNode = nodeNum - } - case err := <-c.Ctx.Done(): - log.Error("MtChallenge eigenDa sequencer service shutting down", "err", err) - return - } - } -} +// +//import ( +// "bytes" +// "context" +// "crypto/ecdsa" +// "encoding/hex" +// "fmt" +// "math/big" +// "strconv" +// "strings" +// "sync" +// "time" +// +// "github.com/pkg/errors" +// "github.com/shurcooL/graphql" +// "google.golang.org/grpc" +// +// datalayr "github.com/Layr-Labs/datalayr/common/contracts" +// gkzg "github.com/Layr-Labs/datalayr/common/crypto/go-kzg-bn254" +// "github.com/Layr-Labs/datalayr/common/graphView" +// "github.com/Layr-Labs/datalayr/common/header" +// pb "github.com/Layr-Labs/datalayr/common/interfaces/interfaceRetrieverServer" +// "github.com/Layr-Labs/datalayr/common/logging" +// +// "github.com/ethereum/go-ethereum/accounts/abi" +// "github.com/ethereum/go-ethereum/accounts/abi/bind" +// ethc "github.com/ethereum/go-ethereum/common" +// "github.com/ethereum/go-ethereum/core/types" +// "github.com/ethereum/go-ethereum/crypto" +// "github.com/ethereum/go-ethereum/ethclient" +// "github.com/ethereum/go-ethereum/log" +// "github.com/ethereum/go-ethereum/rlp" +// +// "github.com/mantlenetworkio/mantle/l2geth/common" +// l2types "github.com/mantlenetworkio/mantle/l2geth/core/types" +// l2ethclient "github.com/mantlenetworkio/mantle/l2geth/ethclient" +// l2rlp "github.com/mantlenetworkio/mantle/l2geth/rlp" +// "github.com/mantlenetworkio/mantle/l2geth/rollup/eigenda" +// common4 "github.com/mantlenetworkio/mantle/mt-batcher/services/common" +// "github.com/mantlenetworkio/mantle/mt-batcher/txmgr" +// "github.com/mantlenetworkio/mantle/mt-challenger/bindings" +// rc "github.com/mantlenetworkio/mantle/mt-challenger/bindings" +// "github.com/mantlenetworkio/mantle/mt-challenger/challenger/client" +// "github.com/mantlenetworkio/mantle/mt-challenger/challenger/db" +// "github.com/mantlenetworkio/mantle/mt-challenger/metrics" +//) +// +//const fraudString = "2d5f2860204f2060295f2d202d5f2860206f2060295f2d202d5f286020512060295f2d2042495444414f204a5553542052454b5420594f55207c5f2860204f2060295f7c202d207c5f2860206f2060295f7c202d207c5f286020512060295f7c" +// +//type SignerFn func(context.Context, ethc.Address, *types.Transaction) (*types.Transaction, error) +// +//var ( +// errMaxPriorityFeePerGasNotFound = errors.New( +// "Method eth_maxPriorityFeePerGas not found", +// ) +// FallbackGasTipCap = big.NewInt(1500000000) +//) +// +//var totalDaNode int +// +//type KzgConfig struct { +// G1Path string +// G2Path string +// TableDir string +// NumWorker int +// Order uint64 // Order is the total size of SRS +//} +// +//type Fraud struct { +// StartingIndex int +//} +// +//type DataLayrDisclosureProof struct { +// Header []byte +// Polys [][]byte +// MultirevealProofs []datalayr.MultiRevealProof +// BatchPolyEquivalenceProof [4]*big.Int +// StartingChunkIndex int +//} +// +//type FraudProof struct { +// DataLayrDisclosureProof +// StartingSymbolIndex int +//} +// +//type ChallengerConfig struct { +// L1Client *ethclient.Client +// L2Client *l2ethclient.Client +// L1ChainID *big.Int +// EigenContractAddr ethc.Address +// Logger *logging.Logger +// PrivKey *ecdsa.PrivateKey +// GraphProvider string +// RetrieverSocket string +// DtlClientUrl string +// KzgConfig KzgConfig +// LastStoreNumber uint64 +// Timeout time.Duration +// PollInterval time.Duration +// CompensatePollInterval time.Duration +// DbPath string +// CheckerBatchIndex uint64 +// UpdateBatchIndexStep uint64 +// NeedReRollupBatch string +// ChallengerCheckEnable bool +// ReRollupToolEnable bool +// DataCompensateEnable bool +// SignerFn SignerFn +// ResubmissionTimeout time.Duration +// NumConfirmations uint64 +// SafeAbortNonceTooLowCount uint64 +// Metrics metrics.ChallengerMetrics +// +// EnableHsm bool +// HsmAPIName string +// HsmCreden string +// HsmAddress string +//} +// +//type Challenger struct { +// Ctx context.Context +// Cfg *ChallengerConfig +// EigenDaContract *bindings.BVMEigenDataLayrChain +// RawEigenContract *bind.BoundContract +// WalletAddr ethc.Address +// EigenABI *abi.ABI +// GraphClient *graphView.GraphClient +// GraphqlClient *graphql.Client +// DtlEigenClient client.DtlClient +// LevelDBStore *db.Store +// txMgr txmgr.TxManager +// cancel func() +// wg sync.WaitGroup +// once sync.Once +//} +// +//func NewChallenger(ctx context.Context, cfg *ChallengerConfig) (*Challenger, error) { +// _, cancel := context.WithTimeout(ctx, common4.DefaultTimeout) +// defer cancel() +// eigenContract, err := bindings.NewBVMEigenDataLayrChain( +// ethc.Address(cfg.EigenContractAddr), cfg.L1Client, +// ) +// if err != nil { +// return nil, err +// } +// parsed, err := abi.JSON(strings.NewReader( +// bindings.BVMEigenDataLayrChainABI, +// )) +// if err != nil { +// log.Error("MtChallenger parse eigen layer contract abi fail", "err", err) +// return nil, err +// } +// eignenABI, err := bindings.BVMEigenDataLayrChainMetaData.GetAbi() +// if err != nil { +// log.Error("MtChallenger get eigen layer contract abi fail", "err", err) +// return nil, err +// } +// rawEigenContract := bind.NewBoundContract( +// cfg.EigenContractAddr, parsed, cfg.L1Client, cfg.L1Client, +// cfg.L1Client, +// ) +// +// txManagerConfig := txmgr.Config{ +// ResubmissionTimeout: cfg.ResubmissionTimeout, +// ReceiptQueryInterval: time.Second, +// NumConfirmations: cfg.NumConfirmations, +// SafeAbortNonceTooLowCount: cfg.SafeAbortNonceTooLowCount, +// } +// +// txMgr := txmgr.NewSimpleTxManager(txManagerConfig, cfg.L1Client) +// +// graphClient := graphView.NewGraphClient(cfg.GraphProvider, cfg.Logger) +// graphqlClient := graphql.NewClient(graphClient.GetEndpoint(), nil) +// var walletAddr ethc.Address +// if cfg.EnableHsm { +// walletAddr = ethc.HexToAddress(cfg.HsmAddress) +// } else { +// walletAddr = crypto.PubkeyToAddress(cfg.PrivKey.PublicKey) +// } +// +// levelDBStore, err := db.NewStore(cfg.DbPath) +// if err != nil { +// log.Error("MtChallenger init leveldb fail", "err", err) +// return nil, err +// } +// dtlEigenClient := client.NewDtlClient(cfg.DtlClientUrl) +// if dtlEigenClient == nil { +// return nil, fmt.Errorf("MtChallenger new eigen client fail") +// } +// return &Challenger{ +// Cfg: cfg, +// Ctx: ctx, +// EigenDaContract: eigenContract, +// RawEigenContract: rawEigenContract, +// WalletAddr: walletAddr, +// EigenABI: eignenABI, +// GraphClient: graphClient, +// GraphqlClient: graphqlClient, +// DtlEigenClient: dtlEigenClient, +// LevelDBStore: levelDBStore, +// txMgr: txMgr, +// cancel: cancel, +// }, nil +//} +// +//func (c *Challenger) getDataStoreById(dataStoreId string) (*graphView.DataStore, error) { +// var query struct { +// DataStore graphView.DataStoreGql `graphql:"dataStore(id: $storeId)"` +// } +// variables := map[string]interface{}{ +// "storeId": graphql.String(dataStoreId), +// } +// err := c.GraphqlClient.Query(context.Background(), &query, variables) +// if err != nil { +// log.Error("MtChallenger query data from graphql fail", "err", err) +// return nil, err +// } +// store, err := query.DataStore.Convert() +// if err != nil { +// log.Error("MtChallenger convert data store fail", "err", err) +// return nil, err +// } +// c.Cfg.LastStoreNumber = uint64(store.StoreNumber) +// return store, nil +//} +// +//func (c *Challenger) callRetrieve(store *graphView.DataStore) ([]byte, []datalayr.Frame, error) { +// conn, err := grpc.Dial(c.Cfg.RetrieverSocket, grpc.WithInsecure()) +// if err != nil { +// log.Error("MtChallenger disperser Cannot connect to", "retriever-socket", c.Cfg.RetrieverSocket, "err", err) +// return nil, nil, err +// } +// defer conn.Close() +// client := pb.NewDataRetrievalClient(conn) +// ctx, cancel := context.WithTimeout(context.Background(), c.Cfg.Timeout) +// defer cancel() +// opt := grpc.MaxCallRecvMsgSize(1024 * 1024 * 300) +// request := &pb.FramesAndDataRequest{ +// DataStoreId: store.StoreNumber, +// } +// reply, err := client.RetrieveFramesAndData(ctx, request, opt) +// if err != nil { +// return nil, nil, err +// } +// data := reply.GetData() +// framesBytes := reply.GetFrames() +// header, err := header.DecodeDataStoreHeader(store.Header) +// if err != nil { +// log.Error("MtChallenger Could not decode header", "err", err) +// return nil, nil, err +// } +// frames := make([]datalayr.Frame, header.NumSys+header.NumPar) +// for i, frameBytes := range framesBytes { +// frame, err := datalayr.DecodeFrame(frameBytes) +// if err == nil { +// frames[i] = frame +// } else { +// return nil, nil, errors.New("MtChallenger Does not Contain all the frames") +// } +// } +// return data, frames, nil +//} +// +//// check if the fraud string exists within the data +//func (c *Challenger) checkForFraud(store *graphView.DataStore, data []byte) (*Fraud, bool) { +// dataString := hex.EncodeToString(data) +// index := strings.Index(dataString, fraudString) +// if index != -1 { +// return &Fraud{StartingIndex: index / 2}, true +// } +// return nil, false +//} +// +//func (c *Challenger) constructFraudProof(store *graphView.DataStore, data []byte, fraud *Fraud, frames []datalayr.Frame) (*FraudProof, error) { +// // encode data to frames here +// header, err := header.DecodeDataStoreHeader(store.Header) +// if err != nil { +// c.Cfg.Logger.Printf("MtChallenger Could not decode header %v. %v\n", header, err) +// return nil, err +// } +// config := c.Cfg.KzgConfig +// +// s1 := gkzg.ReadG1Points(config.G1Path, config.Order, config.NumWorker) +// s2 := gkzg.ReadG2Points(config.G2Path, config.Order, config.NumWorker) +// +// dp := datalayr.NewDisclosureProver(s1, s2) +// +// //there are 31 bytes per fr so there are 31*chunkLenE bytes in each chunk +// //so the i'th byte starts at the (i/(31*encoder.EncodingParams.ChunkLenE))'th chunk +// startingChunkIndex := fraud.StartingIndex / int(31*header.Degree) +// //the fraud string ends len(fraudString)/2 bytes later +// endingChunkIndex := (fraud.StartingIndex + len(fraudString)/2) / int(31*header.Degree) +// startingSymbolIndex := fraud.StartingIndex % int(31*header.Degree) +// //do some math to shift this over by the correct number of bytes +// //there are 32 bytes in the actual poly for every 31 bytes in the data, hence (startingSymbolIndex/31)*32 +// //then we shift over by 1 to get past the first 0 byte, and then (startingSymbolIndex % 31) +// startingSymbolIndex = (startingSymbolIndex/31)*32 + 1 + (startingSymbolIndex % 31) +// +// //check frames range +// if startingChunkIndex > len(frames) { +// return nil, fmt.Errorf("startingChunkIndex is out of frames range, startingChunkIndex: %d, len(frames): %d", startingChunkIndex, len(frames)) +// } +// +// //generate parameters for proving data on chain +// //this is +// // polys: the []byte representation of the polynomials +// // multirevealProofs: the openings of each polynomial against the full polynomial commitment +// // batchPolyEquivalenceProof: the proof that the `polys` are in fact represented by the commitments in `multirevealProofs` +// polys, multirevealProofs, batchPolyEquivalenceProof, err := dp.ProveBatchInterpolatingPolyDisclosure(frames[startingChunkIndex:endingChunkIndex+1], store.DataCommitment, store.Header, uint32(startingChunkIndex)) +// if err != nil { +// return nil, err +// } +// +// disclosureProof := DataLayrDisclosureProof{ +// Header: store.Header, +// Polys: polys, +// MultirevealProofs: multirevealProofs, +// BatchPolyEquivalenceProof: batchPolyEquivalenceProof, +// StartingChunkIndex: startingChunkIndex, +// } +// +// return &FraudProof{DataLayrDisclosureProof: disclosureProof, StartingSymbolIndex: startingSymbolIndex}, nil +//} +// +//func (fp *DataLayrDisclosureProof) ToDisclosureProofs() rc.BVMEigenDataLayrChainDisclosureProofs { +// proofs := make([]rc.DataLayrDisclosureLogicMultiRevealProof, 0) +// for _, oldProof := range fp.MultirevealProofs { +// newProof := rc.DataLayrDisclosureLogicMultiRevealProof{ +// InterpolationPoly: rc.BN254G1Point{X: oldProof.InterpolationPolyCommit[0], Y: oldProof.InterpolationPolyCommit[1]}, +// RevealProof: rc.BN254G1Point{X: oldProof.RevealProof[0], Y: oldProof.RevealProof[1]}, +// ZeroPoly: rc.BN254G2Point{ +// //preserve this ordering for dumb precompile reasons +// X: [2]*big.Int{oldProof.ZeroPolyCommit[1], oldProof.ZeroPolyCommit[0]}, +// Y: [2]*big.Int{oldProof.ZeroPolyCommit[3], oldProof.ZeroPolyCommit[2]}, +// }, +// ZeroPolyProof: oldProof.ZeroPolyProof, +// } +// proofs = append(proofs, newProof) +// } +// return rc.BVMEigenDataLayrChainDisclosureProofs{ +// Header: fp.Header, +// FirstChunkNumber: uint32(fp.StartingChunkIndex), +// Polys: fp.Polys, +// MultiRevealProofs: proofs, +// PolyEquivalenceProof: rc.BN254G2Point{ +// //preserve this ordering for dumb precompile reasons +// X: [2]*big.Int{fp.BatchPolyEquivalenceProof[1], fp.BatchPolyEquivalenceProof[0]}, +// Y: [2]*big.Int{fp.BatchPolyEquivalenceProof[3], fp.BatchPolyEquivalenceProof[2]}, +// }, +// } +//} +// +//func (c *Challenger) UpdateGasPrice(ctx context.Context, tx *types.Transaction) (*types.Transaction, error) { +// var opts *bind.TransactOpts +// var err error +// if !c.Cfg.EnableHsm { +// opts, err = bind.NewKeyedTransactorWithChainID( +// c.Cfg.PrivKey, c.Cfg.L1ChainID, +// ) +// } else { +// opts, err = common4.NewHSMTransactOpts(ctx, c.Cfg.HsmAPIName, +// c.Cfg.HsmAddress, c.Cfg.L1ChainID, c.Cfg.HsmCreden) +// } +// if err != nil { +// return nil, err +// } +// opts.Context = ctx +// opts.Nonce = new(big.Int).SetUint64(tx.Nonce()) +// opts.NoSend = true +// +// finalTx, err := c.RawEigenContract.RawTransact(opts, tx.Data()) +// switch { +// case err == nil: +// return finalTx, nil +// +// case c.IsMaxPriorityFeePerGasNotFoundError(err): +// log.Info("MtChallenger eth_maxPriorityFeePerGas is unsupported by current backend, using fallback gasTipCap", "txData", tx.Data()) +// opts.GasTipCap = FallbackGasTipCap +// return c.RawEigenContract.RawTransact(opts, tx.Data()) +// +// default: +// return nil, err +// } +//} +// +//func (c *Challenger) SendTransaction(ctx context.Context, tx *types.Transaction) error { +// return c.Cfg.L1Client.SendTransaction(ctx, tx) +//} +// +//func (c *Challenger) IsMaxPriorityFeePerGasNotFoundError(err error) bool { +// return strings.Contains( +// err.Error(), errMaxPriorityFeePerGasNotFound.Error(), +// ) +//} +// +//func (c *Challenger) ChallengeProveFraud(ctx context.Context, fraudStoreNumber *big.Int, fraudProof *FraudProof, searchData rc.IDataLayrServiceManagerDataStoreSearchData, disclosureProofs rc.BVMEigenDataLayrChainDisclosureProofs) (*types.Transaction, error) { +// balance, err := c.Cfg.L1Client.BalanceAt( +// c.Ctx, ethc.Address(c.WalletAddr), nil, +// ) +// if err != nil { +// log.Error("MtChallenger unable to get current balance", "err", err) +// return nil, err +// } +// log.Info("MtChallenger wallet address balance", "balance", balance) +// nonce64, err := c.Cfg.L1Client.NonceAt( +// c.Ctx, ethc.Address(c.WalletAddr), nil, +// ) +// if err != nil { +// log.Error("MtChallenger unable to get current nonce", "err", err) +// return nil, err +// } +// nonce := new(big.Int).SetUint64(nonce64) +// var opts *bind.TransactOpts +// if !c.Cfg.EnableHsm { +// opts, err = bind.NewKeyedTransactorWithChainID( +// c.Cfg.PrivKey, c.Cfg.L1ChainID, +// ) +// } else { +// opts, err = common4.NewHSMTransactOpts(ctx, c.Cfg.HsmAPIName, +// c.Cfg.HsmAddress, c.Cfg.L1ChainID, c.Cfg.HsmCreden) +// } +// if err != nil { +// return nil, err +// } +// opts.Context = ctx +// opts.Nonce = nonce +// opts.NoSend = true +// tx, err := c.EigenDaContract.ProveFraud(opts, fraudStoreNumber, new(big.Int).SetUint64(uint64(fraudProof.StartingSymbolIndex)), searchData, disclosureProofs) +// switch { +// case err == nil: +// return tx, nil +// +// case c.IsMaxPriorityFeePerGasNotFoundError(err): +// log.Warn("MtChallenger eth_maxPriorityFeePerGas is unsupported by current backend, using fallback gasTipCap") +// opts.GasTipCap = FallbackGasTipCap +// return c.EigenDaContract.ProveFraud(opts, fraudStoreNumber, new(big.Int).SetUint64(uint64(fraudProof.StartingSymbolIndex)), searchData, disclosureProofs) +// +// default: +// return nil, err +// } +//} +// +//func (c *Challenger) postFraudProof(store *graphView.DataStore, fraudProof *FraudProof) (*types.Transaction, error) { +// searchData := rc.IDataLayrServiceManagerDataStoreSearchData{ +// Duration: store.Duration, +// Timestamp: new(big.Int).SetUint64(uint64(store.InitTime)), +// Index: store.Index, +// Metadata: rc.IDataLayrServiceManagerDataStoreMetadata{ +// HeaderHash: store.DataCommitment, +// DurationDataStoreId: store.DurationDataStoreId, +// GlobalDataStoreId: store.StoreNumber, +// BlockNumber: store.ReferenceBlockNumber, +// Fee: store.Fee, +// Confirmer: ethc.Address(common.HexToAddress(store.Confirmer)), +// SignatoryRecordHash: store.SignatoryRecord, +// }, +// } +// disclosureProofs := fraudProof.ToDisclosureProofs() +// fraudStoreNumber, err := c.EigenDaContract.DataStoreIdToRollupStoreNumber(&bind.CallOpts{}, store.StoreNumber) +// if err != nil { +// return nil, err +// } +// +// tx, err := c.ChallengeProveFraud(c.Ctx, fraudStoreNumber, fraudProof, searchData, disclosureProofs) +// if err != nil { +// return nil, err +// } +// updateGasPrice := func(ctx context.Context) (*types.Transaction, error) { +// log.Info("MtChallenger ConfirmData update gas price") +// return c.UpdateGasPrice(ctx, tx) +// } +// receipt, err := c.txMgr.Send( +// c.Ctx, updateGasPrice, c.SendTransaction, +// ) +// if err != nil { +// return nil, err +// } +// log.Info("MtChallenger challenger prove fraud success", "TxHash", receipt.TxHash) +// return tx, nil +//} +// +//func (c *Challenger) makeReRollupBatchTx(ctx context.Context, batchIndex *big.Int) (*types.Transaction, error) { +// balance, err := c.Cfg.L1Client.BalanceAt( +// c.Ctx, ethc.Address(c.WalletAddr), nil, +// ) +// if err != nil { +// log.Error("MtChallenger unable to get current balance", "err", err) +// return nil, err +// } +// log.Info("MtChallenger wallet address balance", "balance", balance) +// c.Cfg.Metrics.BalanceETH().Set(common4.WeiToEth64(balance)) +// nonce64, err := c.Cfg.L1Client.NonceAt( +// c.Ctx, ethc.Address(c.WalletAddr), nil, +// ) +// if err != nil { +// log.Error("MtChallenger unable to get current nonce", "err", err) +// return nil, err +// } +// c.Cfg.Metrics.NonceETH().Inc() +// nonce := new(big.Int).SetUint64(nonce64) +// var opts *bind.TransactOpts +// if !c.Cfg.EnableHsm { +// opts, err = bind.NewKeyedTransactorWithChainID( +// c.Cfg.PrivKey, c.Cfg.L1ChainID, +// ) +// } else { +// opts, err = common4.NewHSMTransactOpts(ctx, c.Cfg.HsmAPIName, +// c.Cfg.HsmAddress, c.Cfg.L1ChainID, c.Cfg.HsmCreden) +// } +// if err != nil { +// return nil, err +// } +// opts.Context = ctx +// opts.Nonce = nonce +// opts.NoSend = true +// +// tx, err := c.EigenDaContract.SubmitReRollUpInfo(opts, batchIndex) +// switch { +// case err == nil: +// return tx, nil +// +// case c.IsMaxPriorityFeePerGasNotFoundError(err): +// log.Warn("MtChallenger eth_maxPriorityFeePerGas is unsupported by current backend, using fallback gasTipCap") +// opts.GasTipCap = FallbackGasTipCap +// return c.EigenDaContract.SubmitReRollUpInfo(opts, batchIndex) +// default: +// return nil, err +// } +//} +// +//func (c *Challenger) submitReRollupBatchIndex(batchIndex *big.Int) (*types.Transaction, error) { +// tx, err := c.makeReRollupBatchTx(c.Ctx, batchIndex) +// if err != nil { +// return nil, err +// } +// updateGasPrice := func(ctx context.Context) (*types.Transaction, error) { +// log.Info("MtChallenger makReRollupBatchTx update gas price") +// return c.UpdateGasPrice(ctx, tx) +// } +// receipt, err := c.txMgr.Send( +// c.Ctx, updateGasPrice, c.SendTransaction, +// ) +// if err != nil { +// return nil, err +// } +// log.Info("MtChallenger submit re-rollup batch index success", "TxHash", receipt.TxHash) +// return tx, nil +//} +// +//func (c *Challenger) GetEigenLayerNode() (int, error) { +// operators, err := c.GraphClient.QueryOperatorsByStatus() +// if err != nil { +// log.Error("MtChallenger query operators fail", "err", err) +// return 0, err +// } +// return len(operators), nil +//} +// +//func (c *Challenger) ServiceInit() error { +// nodeNum, err := c.GetEigenLayerNode() +// if err != nil { +// log.Error("MtChallenger get batch index fail", "err", err) +// return err +// } +// totalDaNode = nodeNum +// walletBalance, err := c.Cfg.L1Client.BalanceAt( +// c.Ctx, c.WalletAddr, nil, +// ) +// if err != nil { +// log.Warn("Get rollup wallet address balance fail", "err", err) +// return err +// } +// c.Cfg.Metrics.BalanceETH().Set(common4.WeiToEth64(walletBalance)) +// nonce, err := c.Cfg.L1Client.NonceAt( +// c.Ctx, c.WalletAddr, nil, +// ) +// if err != nil { +// log.Warn("Get rollup wallet address nonce fail", "err", err) +// return err +// } +// c.Cfg.Metrics.NonceETH().Set(float64(nonce)) +// return nil +//} +// +//func (c *Challenger) Start() error { +// err := c.ServiceInit() +// if err != nil { +// log.Error("service init error", "err", err) +// return err +// } +// if c.Cfg.ChallengerCheckEnable { +// c.wg.Add(1) +// go c.eventLoop() +// } +// if c.Cfg.DataCompensateEnable { +// c.wg.Add(1) +// go c.dataCompensateForDlNodeExitsLoop() +// } +// c.once.Do(func() { +// log.Info("MtChallenger start exec once update da tool") +// if c.Cfg.ReRollupToolEnable { +// reRollupBatchIndex := strings.Split(c.Cfg.NeedReRollupBatch, "|") +// for index := 0; index < len(reRollupBatchIndex); index++ { +// bigParam := new(big.Int) +// bigBatchIndex, ok := bigParam.SetString(reRollupBatchIndex[index], 10) +// if !ok { +// log.Error("MtChallenger string to big.int fail", "ok", ok) +// continue +// } +// tx, err := c.submitReRollupBatchIndex(bigBatchIndex) +// if err != nil { +// log.Error("MtChallenger tool submit re-rollup info fail", "batchIndex", reRollupBatchIndex[index], "err", err) +// continue +// } +// c.Cfg.Metrics.ReRollupBatchIndex().Set(float64(bigBatchIndex.Uint64())) +// log.Info("MtChallenger tool submit re-rollup info success", "batchIndex", reRollupBatchIndex[index], "txHash", tx.Hash().String()) +// updBatchIndex, err := strconv.ParseUint(reRollupBatchIndex[index], 10, 64) +// if err != nil { +// log.Error("MtChallenger tool type string to uint64 fail") +// } +// c.LevelDBStore.SetLatestBatchIndex(updBatchIndex) +// } +// } +// }) +// return nil +//} +// +//func (c *Challenger) Stop() { +// c.cancel() +// c.wg.Wait() +//} +// +//func (c *Challenger) eventLoop() { +// defer c.wg.Done() +// ticker := time.NewTicker(c.Cfg.PollInterval) +// defer ticker.Stop() +// for { +// select { +// case <-ticker.C: +// latestBatchIndex, err := c.EigenDaContract.RollupBatchIndex(&bind.CallOpts{}) +// if err != nil { +// log.Error("MtChallenger get batch index fail", "err", err) +// continue +// } +// batchIndex, ok := c.LevelDBStore.GetLatestBatchIndex() +// if !ok { +// log.Error("MtChallenger get batch index from db fail", "err", err) +// continue +// } +// if c.Cfg.CheckerBatchIndex > latestBatchIndex.Uint64() { +// log.Info("MtChallenger Batch Index", "DbBatchIndex", batchIndex, "ContractBatchIndex", latestBatchIndex.Uint64()-c.Cfg.CheckerBatchIndex) +// continue +// } +// if batchIndex >= (latestBatchIndex.Uint64() - c.Cfg.CheckerBatchIndex) { +// log.Info("MtChallenger db batch index and contract batch idnex is equal", "DbBatchIndex", batchIndex, "ContractBatchIndex", latestBatchIndex.Uint64()-c.Cfg.CheckerBatchIndex) +// continue +// } +// log.Info("MtChallenger db batch index and contract batch idnex", +// "DbBatchIndex", batchIndex, "ContractBatchIndex", latestBatchIndex.Uint64(), +// "latestBatchIndex.Uint64() - c.Cfg.CheckerBatchIndex", latestBatchIndex.Uint64()-c.Cfg.CheckerBatchIndex, +// ) +// c.Cfg.Metrics.CheckBatchIndex().Set(float64(latestBatchIndex.Uint64() - c.Cfg.CheckerBatchIndex)) +// for i := batchIndex; i <= (latestBatchIndex.Uint64() - c.Cfg.CheckerBatchIndex); i++ { +// dataStoreId, err := c.EigenDaContract.GetRollupStoreByRollupBatchIndex(&bind.CallOpts{}, big.NewInt(int64(i))) +// if err != nil { +// continue +// } +// if dataStoreId.DataStoreId == 0 { +// log.Info("MtChallenger get rollup store id", "DataStoreId", dataStoreId.DataStoreId) +// continue +// } +// store, err := c.getDataStoreById(strconv.Itoa(int(dataStoreId.DataStoreId))) +// if err != nil { +// log.Error("MtChallenger get data store fail", "err", err) +// continue +// } +// log.Info("MtChallenger get data store by id success", "Confirmed", store.Confirmed) +// if store.Confirmed { +// data, frames, err := c.callRetrieve(store) +// if err != nil { +// log.Error("MtChallenger error getting data", "err", err) +// continue +// } +// batchTxn := new([]eigenda.BatchTx) +// batchRlpStream := rlp.NewStream(bytes.NewBuffer(data), uint64(len(data))) +// err = batchRlpStream.Decode(batchTxn) +// if err != nil { +// log.Error("MtChallenger decode batch txn fail", "err", err) +// continue +// } +// newBatchTxn := *batchTxn +// for i := 0; i < len(newBatchTxn); i++ { +// l2Tx := new(l2types.Transaction) +// rlpStream := l2rlp.NewStream(bytes.NewBuffer(newBatchTxn[i].RawTx), 0) +// if err := l2Tx.DecodeRLP(rlpStream); err != nil { +// c.Cfg.Logger.Error().Err(err).Msg("Decode RLP fail") +// } +// +// // tx check for tmp, will remove in future +// l2Transaction, _, err := c.Cfg.L2Client.TransactionByHash(c.Ctx, l2Tx.Hash()) +// if err != nil { +// log.Error("MtChallenger no this transaction", "err", err) +// continue +// } +// log.Info("MtChallenger fond transaction", "hash", l2Transaction.Hash().Hex()) +// } +// +// // check if the fraud string exists within the data +// fraud, exists := c.checkForFraud(store, data) +// if !exists { +// log.Info("MtChallenger no fraud") +// c.LevelDBStore.SetLatestBatchIndex(i) +// continue +// } +// proof, err := c.constructFraudProof(store, data, fraud, frames) +// if err != nil { +// log.Error("MtChallenger error constructing fraud", "err", err) +// continue +// } +// tx, err := c.postFraudProof(store, proof) +// if err != nil { +// log.Error("MtChallenger error posting fraud proof", "err", err) +// continue +// } +// log.Info("MtChallenger fraud proof tx", "hash", tx.Hash().Hex()) +// } +// c.LevelDBStore.SetLatestBatchIndex(i) +// } +// case err := <-c.Ctx.Done(): +// log.Error("MtChallenger eigenDa sequencer service shutting down", "err", err) +// return +// } +// } +//} +// +//func (c *Challenger) dataCompensateForDlNodeExitsLoop() { +// defer c.wg.Done() +// ticker := time.NewTicker(c.Cfg.CompensatePollInterval) +// defer ticker.Stop() +// for { +// select { +// case <-ticker.C: +// nodeNum, err := c.GetEigenLayerNode() +// if err != nil { +// log.Error("MtChallenger data compensate get da node", "err", err) +// continue +// } +// if nodeNum == totalDaNode { +// log.Info("MtChallenger current da node and history da node", "current", nodeNum, "history", totalDaNode) +// continue +// } else { +// // get dtl latest batch index sync from da retriver +// dtlBatchIndex, batchErr := c.DtlEigenClient.GetLatestTransactionBatchIndex() +// if err != nil { +// log.Error("MtChallenger get latest batch index fail", "dtlBatchIndex", dtlBatchIndex, "batchErr", batchErr) +// continue +// } +// contractBatchIndex, batchContractErr := c.EigenDaContract.RollupBatchIndex(&bind.CallOpts{}) +// if err != nil { +// log.Error("MtChallenger get latest batch from contract fail", "contractBatchIndex", contractBatchIndex, "batchErr", batchContractErr) +// continue +// } +// if dtlBatchIndex != 0 { +// var updateEndBatchIndex uint64 +// if dtlBatchIndex+c.Cfg.UpdateBatchIndexStep > contractBatchIndex.Uint64() { +// updateEndBatchIndex = dtlBatchIndex + c.Cfg.UpdateBatchIndexStep +// } else { +// updateEndBatchIndex = contractBatchIndex.Uint64() +// } +// for batchIndex := dtlBatchIndex; batchIndex <= updateEndBatchIndex; batchIndex++ { +// bigParam := new(big.Int) +// bigBatchIndex, ok := bigParam.SetString(strconv.FormatUint(batchIndex, 10), 10) +// if !ok { +// log.Error("MtChallenger string to big.int fail", "ok", ok) +// continue +// } +// tx, err := c.submitReRollupBatchIndex(bigBatchIndex) +// if err != nil { +// log.Error("MtChallenger data compensate submit re-rollup info fail", "batchIndex", bigBatchIndex, "err", err) +// continue +// } +// c.Cfg.Metrics.ReRollupBatchIndex().Set(float64(bigBatchIndex.Uint64())) +// log.Info("MtChallenger tool submit re-rollup info success", "batchIndex", bigBatchIndex, "txHash", tx.Hash().String()) +// } +// } +// totalDaNode = nodeNum +// } +// case err := <-c.Ctx.Done(): +// log.Error("MtChallenge eigenDa sequencer service shutting down", "err", err) +// return +// } +// } +//} diff --git a/mt-challenger/config.go b/mt-challenger/config.go index 6738bfd0b..ba402cff9 100644 --- a/mt-challenger/config.go +++ b/mt-challenger/config.go @@ -5,8 +5,6 @@ import ( "github.com/urfave/cli" - "github.com/Layr-Labs/datalayr/common/logging" - "github.com/mantlenetworkio/mantle/mt-challenger/challenger" "github.com/mantlenetworkio/mantle/mt-challenger/flags" ) @@ -38,14 +36,14 @@ type Config struct { ResubmissionTimeout time.Duration NumConfirmations uint64 SafeAbortNonceTooLowCount uint64 - LoggingConfig logging.Config - MetricsServerEnable bool - MetricsHostname string - MetricsPort uint64 - EnableHsm bool - HsmAPIName string - HsmCreden string - HsmAddress string + // LoggingConfig logging.Config + MetricsServerEnable bool + MetricsHostname string + MetricsPort uint64 + EnableHsm bool + HsmAPIName string + HsmCreden string + HsmAddress string } func NewConfig(ctx *cli.Context) (Config, error) { @@ -71,25 +69,25 @@ func NewConfig(ctx *cli.Context) (Config, error) { ResubmissionTimeout: ctx.GlobalDuration(flags.ResubmissionTimeoutFlag.Name), NumConfirmations: ctx.GlobalUint64(flags.NumConfirmationsFlag.Name), SafeAbortNonceTooLowCount: ctx.GlobalUint64(flags.SafeAbortNonceTooLowCountFlag.Name), - LoggingConfig: logging.ReadCLIConfig(ctx), - FromStoreNumber: ctx.GlobalUint64(flags.StartStoreNumFlag.Name), - PollInterval: ctx.GlobalDuration(flags.PollIntervalFlag.Name), - CompensatePollInterval: ctx.GlobalDuration(flags.CompensatePollIntervalFlag.Name), - DbPath: ctx.GlobalString(flags.DbPathFlag.Name), - CheckerBatchIndex: ctx.GlobalUint64(flags.CheckerBatchIndexFlag.Name), - UpdateBatchIndexStep: ctx.GlobalUint64(flags.UpdateBatchIndexStepFlag.Name), - NeedReRollupBatch: ctx.GlobalString(flags.NeedReRollupBatchFlag.Name), - ChallengerCheckEnable: ctx.GlobalBool(flags.ChallengerCheckEnableFlag.Name), - ReRollupToolEnable: ctx.GlobalBool(flags.ReRollupToolEnableFlag.Name), - DataCompensateEnable: ctx.GlobalBool(flags.DataCompensateEnableFlag.Name), - DisableHTTP2: ctx.GlobalBool(flags.HTTP2DisableFlag.Name), - MetricsServerEnable: ctx.GlobalBool(flags.MetricsServerEnableFlag.Name), - MetricsHostname: ctx.GlobalString(flags.MetricsHostnameFlag.Name), - MetricsPort: ctx.GlobalUint64(flags.MetricsPortFlag.Name), - EnableHsm: ctx.GlobalBool(flags.EnableHsmFlag.Name), - HsmAddress: ctx.GlobalString(flags.HsmAddressFlag.Name), - HsmAPIName: ctx.GlobalString(flags.HsmAPINameFlag.Name), - HsmCreden: ctx.GlobalString(flags.HsmCredenFlag.Name), + // LoggingConfig: logging.ReadCLIConfig(ctx), + FromStoreNumber: ctx.GlobalUint64(flags.StartStoreNumFlag.Name), + PollInterval: ctx.GlobalDuration(flags.PollIntervalFlag.Name), + CompensatePollInterval: ctx.GlobalDuration(flags.CompensatePollIntervalFlag.Name), + DbPath: ctx.GlobalString(flags.DbPathFlag.Name), + CheckerBatchIndex: ctx.GlobalUint64(flags.CheckerBatchIndexFlag.Name), + UpdateBatchIndexStep: ctx.GlobalUint64(flags.UpdateBatchIndexStepFlag.Name), + NeedReRollupBatch: ctx.GlobalString(flags.NeedReRollupBatchFlag.Name), + ChallengerCheckEnable: ctx.GlobalBool(flags.ChallengerCheckEnableFlag.Name), + ReRollupToolEnable: ctx.GlobalBool(flags.ReRollupToolEnableFlag.Name), + DataCompensateEnable: ctx.GlobalBool(flags.DataCompensateEnableFlag.Name), + DisableHTTP2: ctx.GlobalBool(flags.HTTP2DisableFlag.Name), + MetricsServerEnable: ctx.GlobalBool(flags.MetricsServerEnableFlag.Name), + MetricsHostname: ctx.GlobalString(flags.MetricsHostnameFlag.Name), + MetricsPort: ctx.GlobalUint64(flags.MetricsPortFlag.Name), + EnableHsm: ctx.GlobalBool(flags.EnableHsmFlag.Name), + HsmAddress: ctx.GlobalString(flags.HsmAddressFlag.Name), + HsmAPIName: ctx.GlobalString(flags.HsmAPINameFlag.Name), + HsmCreden: ctx.GlobalString(flags.HsmCredenFlag.Name), } return cfg, nil } diff --git a/mt-challenger/flags/flags.go b/mt-challenger/flags/flags.go index 37f439d06..d0f326102 100644 --- a/mt-challenger/flags/flags.go +++ b/mt-challenger/flags/flags.go @@ -2,8 +2,6 @@ package flags import ( "github.com/urfave/cli" - - "github.com/Layr-Labs/datalayr/common/logging" ) const envVarPrefix = "DA_CHALLENGER" @@ -274,7 +272,8 @@ var optionalFlags = []cli.Flag{ func init() { Flags = append(requiredFlags, optionalFlags...) - Flags = append(Flags, logging.CLIFlags(envVarPrefix)...) + //Flags = append(Flags, logging.CLIFlags(envVarPrefix)...) + _ = Flags } var Flags []cli.Flag diff --git a/mt-challenger/go.mod b/mt-challenger/go.mod index af64e0186..e66c1f9cb 100644 --- a/mt-challenger/go.mod +++ b/mt-challenger/go.mod @@ -2,9 +2,9 @@ module github.com/mantlenetworkio/mantle/mt-challenger go 1.19 -replace github.com/Layr-Labs/datalayr/common => ../datalayr/common - -replace github.com/Layr-Labs/datalayr/lib/merkzg => ../datalayr/lib/merkzg +//replace github.com/Layr-Labs/datalayr/common => ../datalayr/common +// +//replace github.com/Layr-Labs/datalayr/lib/merkzg => ../datalayr/lib/merkzg replace github.com/mantlenetworkio/mantle/mt-batcher => ../mt-batcher @@ -17,7 +17,7 @@ replace github.com/mantlenetworkio/mantle/metrics => ../metrics replace github.com/mantlenetworkio/mantle/bss-core => ../bss-core require ( - github.com/Layr-Labs/datalayr/common v0.0.0 + // github.com/Layr-Labs/datalayr/common v0.0.0 github.com/ethereum/go-ethereum v1.10.26 github.com/go-resty/resty/v2 v2.7.0 github.com/mantlenetworkio/mantle/l2geth v0.0.0 @@ -36,7 +36,7 @@ require ( cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v1.0.1 // indirect cloud.google.com/go/kms v1.11.0 // indirect - github.com/Layr-Labs/datalayr/lib/merkzg v0.0.0 // indirect + // github.com/Layr-Labs/datalayr/lib/merkzg v0.0.0 // indirect github.com/VictoriaMetrics/fastcache v1.9.0 // indirect github.com/aristanetworks/goarista v0.0.0-20170210015632-ea17b1a17847 // indirect github.com/beorn7/perks v1.0.1 // indirect diff --git a/mt-challenger/mt_challenger.go b/mt-challenger/mt_challenger.go index c407f8e27..8b5b23145 100644 --- a/mt-challenger/mt_challenger.go +++ b/mt-challenger/mt_challenger.go @@ -6,7 +6,6 @@ import ( "github.com/urfave/cli" - "github.com/Layr-Labs/datalayr/common/logging" ethc "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/log" @@ -26,7 +25,7 @@ func Main(gitVersion string) func(ctx *cli.Context) error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - logger, err := logging.GetLogger(cfg.LoggingConfig) + // logger, err := logging.GetLogger(cfg.LoggingConfig) if err != nil { return err } @@ -61,11 +60,11 @@ func Main(gitVersion string) func(ctx *cli.Context) error { } challengerConfig := &challenger.ChallengerConfig{ - L1Client: l1Client, - L2Client: l2Client, - L1ChainID: chainID, - EigenContractAddr: ethc.Address(common.HexToAddress(cfg.EigenContractAddress)), - Logger: logger, + L1Client: l1Client, + L2Client: l2Client, + L1ChainID: chainID, + EigenContractAddr: ethc.Address(common.HexToAddress(cfg.EigenContractAddress)), + // Logger: logger, PrivKey: challengerPrivKey, GraphProvider: cfg.GraphProvider, RetrieverSocket: cfg.RetrieverSocket,