diff --git a/block/block-manager.md b/block/block-manager.md index 978ceb33eb..1b118a5c98 100644 --- a/block/block-manager.md +++ b/block/block-manager.md @@ -53,7 +53,7 @@ config|config.BlockManagerConfig|block manager configurations (see config option genesis|*cmtypes.GenesisDoc|initialize the block manager with genesis state (genesis configuration defined in `config/genesis.json` file under the app directory) store|store.Store|local datastore for storing rollup blocks and states (default local store path is `$db_dir/rollkit` and `db_dir` specified in the `config.toml` file under the app directory) mempool, proxyapp, eventbus|mempool.Mempool, proxy.AppConnConsensus, *cmtypes.EventBus|for initializing the executor (state transition function). mempool is also used in the manager to check for availability of transactions for lazy block production -dalc|da.DataAvailabilityLayerClient|the data availability light client used to submit and retrieve blocks to DA network +dalc|da.DAClient|the data availability light client used to submit and retrieve blocks to DA network blockstore|*goheaderstore.Store[*types.Block]|to retrieve blocks gossiped over the P2P network Block manager configuration options: @@ -63,7 +63,6 @@ Block manager configuration options: |BlockTime|time.Duration|time interval used for block production and block retrieval from block store ([`defaultBlockTime`][defaultBlockTime])| |DABlockTime|time.Duration|time interval used for both block publication to DA network and block retrieval from DA network ([`defaultDABlockTime`][defaultDABlockTime])| |DAStartHeight|uint64|block retrieval from DA network starts from this height| -|NamespaceID|bytes|8 `byte` unique identifier of the rollup| ### Block Production diff --git a/block/manager.go b/block/manager.go index 34ab0741ec..c4197de526 100644 --- a/block/manager.go +++ b/block/manager.go @@ -66,8 +66,7 @@ type Manager struct { executor *state.BlockExecutor - dalc da.DataAvailabilityLayerClient - retriever da.BlockRetriever + dalc *da.DAClient // daHeight is the height of the latest processed DA block daHeight uint64 @@ -112,7 +111,7 @@ func NewManager( store store.Store, mempool mempool.Mempool, proxyApp proxy.AppConnConsensus, - dalc da.DataAvailabilityLayerClient, + dalc *da.DAClient, eventBus *cmtypes.EventBus, logger log.Logger, blockStore *goheaderstore.Store[*types.Block], @@ -140,7 +139,7 @@ func NewManager( conf.BlockTime = defaultBlockTime } - exec := state.NewBlockExecutor(proposerAddress, conf.NamespaceID, genesis.ChainID, mempool, proxyApp, eventBus, logger) + exec := state.NewBlockExecutor(proposerAddress, genesis.ChainID, mempool, proxyApp, eventBus, logger) if s.LastBlockHeight+1 == uint64(genesis.InitialHeight) { res, err := exec.InitChain(genesis) if err != nil { @@ -168,7 +167,6 @@ func NewManager( store: store, executor: exec, dalc: dalc, - retriever: dalc.(da.BlockRetriever), // TODO(tzdybal): do it in more gentle way (after MVP) daHeight: s.DAHeight, // channels are buffered to avoid blocking on input/output operations, buffer sizes are arbitrary HeaderCh: make(chan *types.SignedHeader, channelLength), @@ -197,9 +195,8 @@ func getAddress(key crypto.PrivKey) ([]byte, error) { } // SetDALC is used to set DataAvailabilityLayerClient used by Manager. -func (m *Manager) SetDALC(dalc da.DataAvailabilityLayerClient) { +func (m *Manager) SetDALC(dalc *da.DAClient) { m.dalc = dalc - m.retriever = dalc.(da.BlockRetriever) } // GetStoreHeight returns the manager's store height @@ -525,7 +522,7 @@ func (m *Manager) processNextDABlock(ctx context.Context) error { func (m *Manager) fetchBlock(ctx context.Context, daHeight uint64) (da.ResultRetrieveBlocks, error) { var err error - blockRes := m.retriever.RetrieveBlocks(ctx, daHeight) + blockRes := m.dalc.RetrieveBlocks(ctx, daHeight) switch blockRes.Code { case da.StatusError: err = fmt.Errorf("failed to retrieve block: %s", blockRes.Message) diff --git a/block/manager_test.go b/block/manager_test.go index 055a972de8..4a9d93ed81 100644 --- a/block/manager_test.go +++ b/block/manager_test.go @@ -6,15 +6,14 @@ import ( "testing" "time" - "github.com/cometbft/cometbft/libs/log" cmtypes "github.com/cometbft/cometbft/types" "github.com/libp2p/go-libp2p/core/crypto" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + goDATest "github.com/rollkit/go-da/test" "github.com/rollkit/rollkit/config" "github.com/rollkit/rollkit/da" - mockda "github.com/rollkit/rollkit/da/mock" "github.com/rollkit/rollkit/store" test "github.com/rollkit/rollkit/test/log" "github.com/rollkit/rollkit/types" @@ -71,18 +70,14 @@ func TestInitialState(t *testing.T) { key, _, _ := crypto.GenerateEd25519Key(rand.Reader) conf := config.BlockManagerConfig{ - BlockTime: 10 * time.Second, - NamespaceID: types.NamespaceID{1, 2, 3, 4, 5, 6, 7, 8}, + BlockTime: 10 * time.Second, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { assert := assert.New(t) logger := test.NewFileLoggerCustom(t, test.TempLogFileName(t, c.name)) - dalc := getMockDALC(logger) - defer func() { - require.NoError(t, dalc.Stop()) - }() + dalc := &da.DAClient{DA: goDATest.NewDummyDA(), Logger: logger} agg, err := NewManager(key, conf, c.genesis, c.store, nil, nil, dalc, nil, logger, nil) assert.NoError(err) assert.NotNil(agg) @@ -95,13 +90,6 @@ func TestInitialState(t *testing.T) { } } -func getMockDALC(logger log.Logger) da.DataAvailabilityLayerClient { - dalc := &mockda.DataAvailabilityLayerClient{} - _ = dalc.Init([8]byte{}, nil, nil, logger) - _ = dalc.Start() - return dalc -} - func TestIsDAIncluded(t *testing.T) { require := require.New(t) diff --git a/config/config.go b/config/config.go index 346e36fbe7..1e5ea52b43 100644 --- a/config/config.go +++ b/config/config.go @@ -1,25 +1,20 @@ package config import ( - "encoding/hex" "time" cmcfg "github.com/cometbft/cometbft/config" "github.com/spf13/cobra" "github.com/spf13/viper" - - "github.com/rollkit/rollkit/types" ) const ( flagAggregator = "rollkit.aggregator" - flagDALayer = "rollkit.da_layer" - flagDAConfig = "rollkit.da_config" + flagDAAddress = "rollkit.da_address" flagBlockTime = "rollkit.block_time" flagDABlockTime = "rollkit.da_block_time" flagDAStartHeight = "rollkit.da_start_height" - flagNamespaceID = "rollkit.namespace_id" flagLight = "rollkit.light" flagTrustedHash = "rollkit.trusted_hash" flagLazyAggregator = "rollkit.lazy_aggregator" @@ -35,8 +30,7 @@ type NodeConfig struct { // parameters below are Rollkit specific and read from config Aggregator bool `mapstructure:"aggregator"` BlockManagerConfig `mapstructure:",squash"` - DALayer string `mapstructure:"da_layer"` - DAConfig string `mapstructure:"da_config"` + DAAddress string `mapstructure:"da_address"` Light bool `mapstructure:"light"` HeaderConfig `mapstructure:",squash"` LazyAggregator bool `mapstructure:"lazy_aggregator"` @@ -54,8 +48,7 @@ type BlockManagerConfig struct { // DABlockTime informs about block time of underlying data availability layer DABlockTime time.Duration `mapstructure:"da_block_time"` // DAStartHeight allows skipping first DAStartHeight-1 blocks when querying for blocks. - DAStartHeight uint64 `mapstructure:"da_start_height"` - NamespaceID types.NamespaceID `mapstructure:"namespace_id"` + DAStartHeight uint64 `mapstructure:"da_start_height"` } // GetNodeConfig translates Tendermint's configuration into Rollkit configuration. @@ -87,19 +80,12 @@ func GetNodeConfig(nodeConf *NodeConfig, cmConf *cmcfg.Config) { // This method is called in cosmos-sdk. func (nc *NodeConfig) GetViperConfig(v *viper.Viper) error { nc.Aggregator = v.GetBool(flagAggregator) - nc.DALayer = v.GetString(flagDALayer) - nc.DAConfig = v.GetString(flagDAConfig) + nc.DAAddress = v.GetString(flagDAAddress) nc.DAStartHeight = v.GetUint64(flagDAStartHeight) nc.DABlockTime = v.GetDuration(flagDABlockTime) nc.BlockTime = v.GetDuration(flagBlockTime) nc.LazyAggregator = v.GetBool(flagLazyAggregator) - nsID := v.GetString(flagNamespaceID) nc.Light = v.GetBool(flagLight) - bytes, err := hex.DecodeString(nsID) - if err != nil { - return err - } - copy(nc.NamespaceID[:], bytes) nc.TrustedHash = v.GetString(flagTrustedHash) return nil } @@ -111,12 +97,10 @@ func AddFlags(cmd *cobra.Command) { def := DefaultNodeConfig cmd.Flags().Bool(flagAggregator, def.Aggregator, "run node in aggregator mode") cmd.Flags().Bool(flagLazyAggregator, def.LazyAggregator, "wait for transactions, don't build empty blocks") - cmd.Flags().String(flagDALayer, def.DALayer, "Data Availability Layer Client name (mock or grpc") - cmd.Flags().String(flagDAConfig, def.DAConfig, "Data Availability Layer Client config") + cmd.Flags().String(flagDAAddress, def.DAAddress, "DA address (host:port)") cmd.Flags().Duration(flagBlockTime, def.BlockTime, "block time (for aggregator mode)") cmd.Flags().Duration(flagDABlockTime, def.DABlockTime, "DA chain block time (for syncing)") cmd.Flags().Uint64(flagDAStartHeight, def.DAStartHeight, "starting DA block height (for syncing)") - cmd.Flags().BytesHex(flagNamespaceID, def.NamespaceID[:], "namespace identifies (8 bytes in hex)") cmd.Flags().Bool(flagLight, def.Light, "run light client") cmd.Flags().String(flagTrustedHash, def.TrustedHash, "initial trusted hash to start the header exchange service") } diff --git a/config/config_test.go b/config/config_test.go index 109c0ad2cd..a9a04ecb2d 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -9,8 +9,6 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/stretchr/testify/assert" - - "github.com/rollkit/rollkit/types" ) func TestGetNodeConfig(t *testing.T) { @@ -47,17 +45,13 @@ func TestViperAndCobra(t *testing.T) { assert.NoError(v.BindPFlags(cmd.Flags())) assert.NoError(cmd.Flags().Set(flagAggregator, "true")) - assert.NoError(cmd.Flags().Set(flagDALayer, "foobar")) - assert.NoError(cmd.Flags().Set(flagDAConfig, `{"json":true}`)) + assert.NoError(cmd.Flags().Set(flagDAAddress, `{"json":true}`)) assert.NoError(cmd.Flags().Set(flagBlockTime, "1234s")) - assert.NoError(cmd.Flags().Set(flagNamespaceID, "0102030405060708")) nc := DefaultNodeConfig assert.NoError(nc.GetViperConfig(v)) assert.Equal(true, nc.Aggregator) - assert.Equal("foobar", nc.DALayer) - assert.Equal(`{"json":true}`, nc.DAConfig) + assert.Equal(`{"json":true}`, nc.DAAddress) assert.Equal(1234*time.Second, nc.BlockTime) - assert.Equal(types.NamespaceID{1, 2, 3, 4, 5, 6, 7, 8}, nc.NamespaceID) } diff --git a/config/defaults.go b/config/defaults.go index 72e0366c3c..505f4da6be 100644 --- a/config/defaults.go +++ b/config/defaults.go @@ -2,8 +2,6 @@ package config import ( "time" - - "github.com/rollkit/rollkit/types" ) const ( @@ -25,11 +23,9 @@ var DefaultNodeConfig = NodeConfig{ BlockManagerConfig: BlockManagerConfig{ BlockTime: 1 * time.Second, DABlockTime: 15 * time.Second, - NamespaceID: types.NamespaceID{}, }, - DALayer: "newda", - DAConfig: "", - Light: false, + DAAddress: ":26650", + Light: false, HeaderConfig: HeaderConfig{ TrustedHash: "", }, diff --git a/da/celestia/celestia.go b/da/celestia/celestia.go deleted file mode 100644 index 84a5ed9b6c..0000000000 --- a/da/celestia/celestia.go +++ /dev/null @@ -1,178 +0,0 @@ -package celestia - -import ( - "context" - "encoding/hex" - "encoding/json" - "strings" - "time" - - "github.com/gogo/protobuf/proto" - ds "github.com/ipfs/go-datastore" - - openrpc "github.com/rollkit/celestia-openrpc" - "github.com/rollkit/celestia-openrpc/types/blob" - "github.com/rollkit/celestia-openrpc/types/share" - - openrpcns "github.com/rollkit/celestia-openrpc/types/namespace" - "github.com/rollkit/rollkit/da" - "github.com/rollkit/rollkit/third_party/log" - "github.com/rollkit/rollkit/types" - pb "github.com/rollkit/rollkit/types/pb/rollkit" -) - -// DataAvailabilityLayerClient use celestia-node public API. -type DataAvailabilityLayerClient struct { - rpc *openrpc.Client - - namespace openrpcns.Namespace - config Config - logger log.Logger -} - -var _ da.DataAvailabilityLayerClient = &DataAvailabilityLayerClient{} -var _ da.BlockRetriever = &DataAvailabilityLayerClient{} - -// Config stores Celestia DALC configuration parameters. -type Config struct { - AuthToken string `json:"auth_token"` - BaseURL string `json:"base_url"` - Timeout time.Duration `json:"timeout"` - Fee int64 `json:"fee"` - GasLimit uint64 `json:"gas_limit"` -} - -// Init initializes DataAvailabilityLayerClient instance. -func (c *DataAvailabilityLayerClient) Init(namespaceID types.NamespaceID, config []byte, kvStore ds.Datastore, logger log.Logger) error { - namespace, err := share.NewBlobNamespaceV0(namespaceID[:]) - if err != nil { - return err - } - c.namespace = namespace.ToAppNamespace() - c.logger = logger - - if len(config) > 0 { - return json.Unmarshal(config, &c.config) - } - - return nil -} - -// Start prepares DataAvailabilityLayerClient to work. -func (c *DataAvailabilityLayerClient) Start() error { - c.logger.Info("starting Celestia Data Availability Layer Client", "baseURL", c.config.BaseURL) - var err error - c.rpc, err = openrpc.NewClient(context.Background(), c.config.BaseURL, c.config.AuthToken) - return err -} - -// Stop stops DataAvailabilityLayerClient. -func (c *DataAvailabilityLayerClient) Stop() error { - c.logger.Info("stopping Celestia Data Availability Layer Client") - return nil -} - -// SubmitBlocks submits blocks to DA layer. -func (c *DataAvailabilityLayerClient) SubmitBlocks(ctx context.Context, blocks []*types.Block) da.ResultSubmitBlocks { - blobs := make([]*blob.Blob, len(blocks)) - for blockIndex, block := range blocks { - data, err := block.MarshalBinary() - if err != nil { - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: err.Error(), - }, - } - } - blockBlob, err := blob.NewBlobV0(c.namespace.Bytes(), data) - if err != nil { - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: err.Error(), - }, - } - } - blobs[blockIndex] = blockBlob - } - - dataLayerHeight, err := c.rpc.Blob.Submit(ctx, blobs, openrpc.DefaultSubmitOptions()) - if err != nil { - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: err.Error(), - }, - } - } - - c.logger.Debug("successfully submitted blobs", "daHeight", dataLayerHeight) - - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusSuccess, - DAHeight: uint64(dataLayerHeight), - }, - } -} - -// RetrieveBlocks gets a batch of blocks from DA layer. -func (c *DataAvailabilityLayerClient) RetrieveBlocks(ctx context.Context, dataLayerHeight uint64) da.ResultRetrieveBlocks { - c.logger.Debug("trying to retrieve blob using Blob.GetAll", "daHeight", dataLayerHeight, "namespace", hex.EncodeToString(c.namespace.Bytes())) - blobs, err := c.rpc.Blob.GetAll(ctx, dataLayerHeight, []share.Namespace{c.namespace.Bytes()}) - status := dataRequestErrorToStatus(err) - if status != da.StatusSuccess { - return da.ResultRetrieveBlocks{ - BaseResult: da.BaseResult{ - Code: status, - Message: err.Error(), - }, - } - } - - blocks := make([]*types.Block, len(blobs)) - for i, blob := range blobs { - var block pb.Block - err = proto.Unmarshal(blob.Data, &block) - if err != nil { - c.logger.Error("failed to unmarshal block", "daHeight", dataLayerHeight, "position", i, "error", err) - continue - } - blocks[i] = new(types.Block) - err := blocks[i].FromProto(&block) - if err != nil { - return da.ResultRetrieveBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: err.Error(), - }, - } - } - } - - return da.ResultRetrieveBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusSuccess, - DAHeight: dataLayerHeight, - }, - Blocks: blocks, - } -} - -func dataRequestErrorToStatus(err error) da.StatusCode { - switch { - case err == nil, - // ErrNamespaceNotFound is a success because it means no retries are necessary, the - // namespace doesn't exist in the block. - // TODO: Once node implements non-inclusion proofs, ErrNamespaceNotFound needs to be verified - strings.Contains(err.Error(), da.ErrNamespaceNotFound.Error()): - return da.StatusSuccess - case strings.Contains(err.Error(), da.ErrDataNotFound.Error()), - strings.Contains(err.Error(), da.ErrEDSNotFound.Error()), - strings.Contains(err.Error(), da.ErrBlobNotFound.Error()): - return da.StatusNotFound - default: - return da.StatusError - } -} diff --git a/da/celestia/celestia_test.go b/da/celestia/celestia_test.go deleted file mode 100644 index b9120a63a8..0000000000 --- a/da/celestia/celestia_test.go +++ /dev/null @@ -1,43 +0,0 @@ -package celestia - -import ( - "errors" - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/rollkit/rollkit/da" -) - -func TestDataRequestErrorToStatus(t *testing.T) { - randErr := errors.New("some random error") - var test = []struct { - statusCode da.StatusCode - err error - }{ - // Status Success Cases - {da.StatusSuccess, nil}, - {da.StatusSuccess, da.ErrNamespaceNotFound}, - {da.StatusSuccess, errors.Join(randErr, da.ErrNamespaceNotFound, randErr)}, - - // TODO: cases that need investigating, are these possible? If - // so, is this the correct status code? - {da.StatusSuccess, errors.Join(da.ErrEDSNotFound, da.ErrNamespaceNotFound)}, - {da.StatusSuccess, errors.Join(da.ErrDataNotFound, da.ErrNamespaceNotFound)}, - - // Status not Found Cases - {da.StatusNotFound, da.ErrDataNotFound}, - {da.StatusNotFound, da.ErrEDSNotFound}, - {da.StatusNotFound, errors.Join(da.ErrEDSNotFound, da.ErrDataNotFound)}, - {da.StatusNotFound, errors.Join(da.ErrEDSNotFound, randErr)}, - {da.StatusNotFound, errors.Join(randErr, da.ErrDataNotFound)}, - - // Status Error Cases - {da.StatusError, randErr}, - } - assert := assert.New(t) - for _, tt := range test { - t.Logf("Testing %v", tt.err) - assert.Equal(tt.statusCode, dataRequestErrorToStatus(tt.err)) - } -} diff --git a/da/celestia/mock/server.go b/da/celestia/mock/server.go deleted file mode 100644 index 7890889a5d..0000000000 --- a/da/celestia/mock/server.go +++ /dev/null @@ -1,231 +0,0 @@ -package mock - -import ( - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/http/httptest" - "time" - - mux2 "github.com/gorilla/mux" - - "github.com/rollkit/celestia-openrpc/types/blob" - "github.com/rollkit/go-da/test" - "github.com/rollkit/rollkit/da/newda" - "github.com/rollkit/rollkit/store" - "github.com/rollkit/rollkit/third_party/log" - "github.com/rollkit/rollkit/types" -) - -// ErrorCode represents RPC error code. -type ErrorCode int - -type respError struct { - Code ErrorCode `json:"code"` - Message string `json:"message"` - Meta json.RawMessage `json:"meta,omitempty"` -} - -// Error returns error message string. -func (e *respError) Error() string { - if e.Code >= -32768 && e.Code <= -32000 { - return fmt.Sprintf("RPC error (%d): %s", e.Code, e.Message) - } - return e.Message -} - -type request struct { - Jsonrpc string `json:"jsonrpc"` - ID interface{} `json:"id,omitempty"` - Method string `json:"method"` - Params json.RawMessage `json:"params"` - Meta map[string]string `json:"meta,omitempty"` -} - -type response struct { - Jsonrpc string `json:"jsonrpc"` - Result interface{} `json:"result,omitempty"` - ID interface{} `json:"id"` - Error *respError `json:"error,omitempty"` -} - -// Server mocks celestia-node HTTP API. -type Server struct { - mock *newda.NewDA - blockTime time.Duration - server *httptest.Server - logger log.Logger -} - -// NewServer creates new instance of Server. -func NewServer(blockTime time.Duration, logger log.Logger) *Server { - return &Server{ - mock: &newda.NewDA{DA: test.NewDummyDA()}, - blockTime: blockTime, - logger: logger, - } -} - -// Start starts HTTP server with given listener. -func (s *Server) Start() (string, error) { - kvStore, err := store.NewDefaultInMemoryKVStore() - if err != nil { - return "", err - } - err = s.mock.Init([8]byte{}, []byte(s.blockTime.String()), kvStore, s.logger) - if err != nil { - return "", err - } - err = s.mock.Start() - if err != nil { - return "", err - } - s.server = httptest.NewServer(s.getHandler()) - s.logger.Debug("http server exited with", "error", err) - return s.server.URL, nil -} - -// Stop shuts down the Server. -func (s *Server) Stop() { - s.server.Close() -} - -func (s *Server) getHandler() http.Handler { - mux := mux2.NewRouter() - mux.HandleFunc("/", s.rpc).Methods(http.MethodPost) - - return mux -} - -func (s *Server) rpc(w http.ResponseWriter, r *http.Request) { - var req request - err := json.NewDecoder(r.Body).Decode(&req) - if err != nil { - s.writeError(w, err) - return - } - switch req.Method { - case "blob.GetAll": - var params []interface{} - err := json.Unmarshal(req.Params, ¶ms) - if err != nil { - s.writeError(w, err) - return - } - if len(params) != 2 { - s.writeError(w, errors.New("expected 2 params: height (uint64), namespace (base64 string)")) - return - } - height := params[0].(float64) - nsBase64 := params[1].([]interface{})[0].(string) - ns, err := base64.StdEncoding.DecodeString(nsBase64) - if err != nil { - s.writeError(w, err) - return - } - block := s.mock.RetrieveBlocks(r.Context(), uint64(height)) - var blobs []blob.Blob - for _, block := range block.Blocks { - data, err := block.MarshalBinary() - if err != nil { - s.writeError(w, err) - return - } - blob, err := blob.NewBlobV0(ns, data) - if err != nil { - s.writeError(w, err) - return - } - blobs = append(blobs, *blob) - } - resp := &response{ - Jsonrpc: "2.0", - Result: blobs, - ID: req.ID, - Error: nil, - } - bytes, err := json.Marshal(resp) - if err != nil { - s.writeError(w, err) - return - } - s.writeResponse(w, bytes) - case "share.SharesAvailable": - resp := &response{ - Jsonrpc: "2.0", - ID: req.ID, - Error: nil, - } - bytes, err := json.Marshal(resp) - if err != nil { - s.writeError(w, err) - return - } - s.writeResponse(w, bytes) - case "blob.Submit": - var params []interface{} - err := json.Unmarshal(req.Params, ¶ms) - if err != nil { - s.writeError(w, err) - return - } - if len(params) != 2 { - s.writeError(w, errors.New("expected 2 params: data (base64 string) and options (map[string]interface{})")) - return - } - // ignores the second parameter - options - blocks := make([]*types.Block, len(params[0].([]interface{}))) - for i, data := range params[0].([]interface{}) { - blockBase64 := data.(map[string]interface{})["data"].(string) - blockData, err := base64.StdEncoding.DecodeString(blockBase64) - if err != nil { - s.writeError(w, err) - return - } - blocks[i] = new(types.Block) - err = blocks[i].UnmarshalBinary(blockData) - if err != nil { - s.writeError(w, err) - return - } - } - - res := s.mock.SubmitBlocks(r.Context(), blocks) - resp := &response{ - Jsonrpc: "2.0", - Result: res.DAHeight, - ID: req.ID, - Error: nil, - } - bytes, err := json.Marshal(resp) - if err != nil { - s.writeError(w, err) - return - } - s.writeResponse(w, bytes) - } -} - -func (s *Server) writeResponse(w http.ResponseWriter, payload []byte) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusOK) - _, err := w.Write(payload) - if err != nil { - s.logger.Error("failed to write response", "error", err) - } -} - -func (s *Server) writeError(w http.ResponseWriter, err error) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(http.StatusInternalServerError) - resp, jerr := json.Marshal(err.Error()) - if jerr != nil { - s.logger.Error("failed to serialize error message", "error", jerr) - } - _, werr := w.Write(resp) - if werr != nil { - s.logger.Error("failed to write response", "error", werr) - } -} diff --git a/da/da.go b/da/da.go index 49f2d2a65b..14eefb955a 100644 --- a/da/da.go +++ b/da/da.go @@ -2,24 +2,20 @@ package da import ( "context" + "encoding/binary" "errors" + "fmt" - ds "github.com/ipfs/go-datastore" + "github.com/gogo/protobuf/proto" + goDA "github.com/rollkit/go-da" "github.com/rollkit/rollkit/third_party/log" "github.com/rollkit/rollkit/types" + pb "github.com/rollkit/rollkit/types/pb/rollkit" ) -var ( - // ErrDataNotFound is used to indicated that requested data failed to be retrieved. - ErrDataNotFound = errors.New("data not found") - // ErrNamespaceNotFound is used to indicate that the block contains data, but not for the requested namespace. - ErrNamespaceNotFound = errors.New("namespace not found in data") - // ErrBlobNotFound is used to indicate that the blob was not found. - ErrBlobNotFound = errors.New("blob: not found") - // ErrEDSNotFound is used to indicate that the EDS was not found. - ErrEDSNotFound = errors.New("eds not found") -) +// ErrBlobNotFound is used to indicate that the blob was not found. +var ErrBlobNotFound = errors.New("blob: not found") // StatusCode is a type for DA layer return status. // TODO: define an enum of different non-happy-path cases @@ -69,27 +65,103 @@ type ResultRetrieveBlocks struct { Blocks []*types.Block } -// DataAvailabilityLayerClient defines generic interface for DA layer block submission. -// It also contains life-cycle methods. -type DataAvailabilityLayerClient interface { - // Init is called once to allow DA client to read configuration and initialize resources. - Init(namespaceID types.NamespaceID, config []byte, kvStore ds.Datastore, logger log.Logger) error - - // Start is called once, after Init. It's implementation should start operation of DataAvailabilityLayerClient. - Start() error +// DAClient is a new DA implementation. +type DAClient struct { + DA goDA.DA + Logger log.Logger +} - // Stop is called once, when DataAvailabilityLayerClient is no longer needed. - Stop() error +// SubmitBlocks submits blocks to DA. +func (dac *DAClient) SubmitBlocks(ctx context.Context, blocks []*types.Block) ResultSubmitBlocks { + blobs := make([][]byte, len(blocks)) + for i := range blocks { + blob, err := blocks[i].MarshalBinary() + if err != nil { + return ResultSubmitBlocks{ + BaseResult: BaseResult{ + Code: StatusError, + Message: "failed to serialize block", + }, + } + } + blobs[i] = blob + } + ids, _, err := dac.DA.Submit(blobs) + if err != nil { + return ResultSubmitBlocks{ + BaseResult: BaseResult{ + Code: StatusError, + Message: "failed to submit blocks: " + err.Error(), + }, + } + } - // SubmitBlocks submits the passed in blocks to the DA layer. - // This should create a transaction which (potentially) - // triggers a state transition in the DA layer. - SubmitBlocks(ctx context.Context, blocks []*types.Block) ResultSubmitBlocks + return ResultSubmitBlocks{ + BaseResult: BaseResult{ + Code: StatusSuccess, + DAHeight: binary.LittleEndian.Uint64(ids[0]), + }, + } } -// BlockRetriever is additional interface that can be implemented by Data Availability Layer Client that is able to retrieve -// block data from DA layer. This gives the ability to use it for block synchronization. -type BlockRetriever interface { - // RetrieveBlocks returns blocks at given data layer height from data availability layer. - RetrieveBlocks(ctx context.Context, dataLayerHeight uint64) ResultRetrieveBlocks +// RetrieveBlocks retrieves blocks from DA. +func (dac *DAClient) RetrieveBlocks(ctx context.Context, dataLayerHeight uint64) ResultRetrieveBlocks { + ids, err := dac.DA.GetIDs(dataLayerHeight) + if err != nil { + return ResultRetrieveBlocks{ + BaseResult: BaseResult{ + Code: StatusError, + Message: fmt.Sprintf("failed to get IDs: %s", err.Error()), + DAHeight: dataLayerHeight, + }, + } + } + // ids can be nil if there are no blocks at the requested height. + if ids == nil { + return ResultRetrieveBlocks{ + BaseResult: BaseResult{ + Code: StatusNotFound, + Message: ErrBlobNotFound.Error(), + }, + } + } + + blobs, err := dac.DA.Get(ids) + if err != nil { + return ResultRetrieveBlocks{ + BaseResult: BaseResult{ + Code: StatusError, + Message: fmt.Sprintf("failed to get blobs: %s", err.Error()), + DAHeight: dataLayerHeight, + }, + } + } + + blocks := make([]*types.Block, len(blobs)) + for i, blob := range blobs { + var block pb.Block + err = proto.Unmarshal(blob, &block) + if err != nil { + dac.Logger.Error("failed to unmarshal block", "daHeight", dataLayerHeight, "position", i, "error", err) + continue + } + blocks[i] = new(types.Block) + err := blocks[i].FromProto(&block) + if err != nil { + return ResultRetrieveBlocks{ + BaseResult: BaseResult{ + Code: StatusError, + Message: err.Error(), + }, + } + } + } + + return ResultRetrieveBlocks{ + BaseResult: BaseResult{ + Code: StatusSuccess, + DAHeight: dataLayerHeight, + }, + Blocks: blocks, + } } diff --git a/da/da_test.go b/da/da_test.go new file mode 100644 index 0000000000..f89db5202f --- /dev/null +++ b/da/da_test.go @@ -0,0 +1,124 @@ +package da + +import ( + "context" + "fmt" + "math/rand" + "net" + "os" + "strconv" + "testing" + "time" + + "github.com/cometbft/cometbft/libs/log" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + + "google.golang.org/grpc/credentials/insecure" + + "github.com/rollkit/go-da/proxy" + goDATest "github.com/rollkit/go-da/test" + "github.com/rollkit/rollkit/types" +) + +const mockDaBlockTime = 100 * time.Millisecond + +func TestMain(m *testing.M) { + srv := startMockGRPCServ() + if srv == nil { + os.Exit(1) + } + exitCode := m.Run() + + // teardown servers + srv.GracefulStop() + + os.Exit(exitCode) +} + +func TestSubmitRetrieve(t *testing.T) { + dummyClient := &DAClient{DA: goDATest.NewDummyDA(), Logger: log.TestingLogger()} + grpcClient, err := startMockGRPCClient() + require.NoError(t, err) + clients := map[string]*DAClient{ + "dummy": dummyClient, + "grpc": grpcClient, + } + for name, dalc := range clients { + t.Run(name, func(t *testing.T) { + doTestSubmitRetrieve(t, dalc) + }) + } +} + +func startMockGRPCServ() *grpc.Server { + srv := proxy.NewServer(goDATest.NewDummyDA(), grpc.Creds(insecure.NewCredentials())) + lis, err := net.Listen("tcp", "127.0.0.1"+":"+strconv.Itoa(7980)) + if err != nil { + fmt.Println(err) + return nil + } + go func() { + _ = srv.Serve(lis) + }() + return srv +} + +func startMockGRPCClient() (*DAClient, error) { + client := proxy.NewClient() + err := client.Start("127.0.0.1:7980", grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + return nil, err + } + return &DAClient{DA: client, Logger: log.TestingLogger()}, nil +} + +func doTestSubmitRetrieve(t *testing.T, dalc *DAClient) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + require := require.New(t) + assert := assert.New(t) + + // wait a bit more than mockDaBlockTime, so mock can "produce" some blocks + time.Sleep(mockDaBlockTime + 20*time.Millisecond) + + countAtHeight := make(map[uint64]int) + blockToDAHeight := make(map[*types.Block]uint64) + numBatches := uint64(10) + blocksSubmittedPerBatch := 10 + + for i := uint64(0); i < numBatches; i++ { + blocks := make([]*types.Block, blocksSubmittedPerBatch) + for j := 0; j < len(blocks); j++ { + blocks[j] = types.GetRandomBlock(i*numBatches+uint64(j), rand.Int()%20) //nolint:gosec + } + resp := dalc.SubmitBlocks(ctx, blocks) + assert.Equal(StatusSuccess, resp.Code, resp.Message) + time.Sleep(time.Duration(rand.Int63() % mockDaBlockTime.Milliseconds())) //nolint:gosec + + for _, b := range blocks { + blockToDAHeight[b] = resp.DAHeight + countAtHeight[resp.DAHeight]++ + } + } + + // wait a bit more than mockDaBlockTime, so mock can "produce" last blocks + time.Sleep(mockDaBlockTime + 20*time.Millisecond) + + for h, cnt := range countAtHeight { + t.Log("Retrieving block, DA Height", h) + ret := dalc.RetrieveBlocks(ctx, h) + assert.Equal(StatusSuccess, ret.Code, ret.Message) + require.NotEmpty(ret.Blocks, h) + assert.Equal(cnt, blocksSubmittedPerBatch) + assert.Len(ret.Blocks, cnt, h) + } + + for b, h := range blockToDAHeight { + ret := dalc.RetrieveBlocks(ctx, h) + assert.Equal(StatusSuccess, ret.Code, h) + require.NotEmpty(ret.Blocks, h) + assert.Contains(ret.Blocks, b, h) + } +} diff --git a/da/grpc/grpc.go b/da/grpc/grpc.go deleted file mode 100644 index 24aa92de8e..0000000000 --- a/da/grpc/grpc.go +++ /dev/null @@ -1,131 +0,0 @@ -package grpc - -import ( - "context" - "encoding/json" - "strconv" - - ds "github.com/ipfs/go-datastore" - "google.golang.org/grpc" - "google.golang.org/grpc/credentials/insecure" - - "github.com/rollkit/rollkit/da" - "github.com/rollkit/rollkit/third_party/log" - "github.com/rollkit/rollkit/types" - "github.com/rollkit/rollkit/types/pb/dalc" - "github.com/rollkit/rollkit/types/pb/rollkit" -) - -// DataAvailabilityLayerClient is a generic client that proxies all DA requests via gRPC. -type DataAvailabilityLayerClient struct { - config Config - - conn *grpc.ClientConn - client dalc.DALCServiceClient - - logger log.Logger -} - -// Config contains configuration options for DataAvailabilityLayerClient. -type Config struct { - // TODO(tzdybal): add more options! - Host string `json:"host"` - Port int `json:"port"` -} - -// DefaultConfig defines default values for DataAvailabilityLayerClient configuration. -var DefaultConfig = Config{ - Host: "127.0.0.1", - Port: 7980, -} - -var _ da.DataAvailabilityLayerClient = &DataAvailabilityLayerClient{} -var _ da.BlockRetriever = &DataAvailabilityLayerClient{} - -// Init sets the configuration options. -func (d *DataAvailabilityLayerClient) Init(_ types.NamespaceID, config []byte, _ ds.Datastore, logger log.Logger) error { - d.logger = logger - if len(config) == 0 { - d.config = DefaultConfig - return nil - } - return json.Unmarshal(config, &d.config) -} - -// Start creates connection to gRPC server and instantiates gRPC client. -func (d *DataAvailabilityLayerClient) Start() error { - d.logger.Info("starting GRPC DALC", "host", d.config.Host, "port", d.config.Port) - var err error - var opts []grpc.DialOption - // TODO(tzdybal): add more options - opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials())) - d.conn, err = grpc.Dial(d.config.Host+":"+strconv.Itoa(d.config.Port), opts...) - if err != nil { - return err - } - - d.client = dalc.NewDALCServiceClient(d.conn) - - return nil -} - -// Stop closes connection to gRPC server. -func (d *DataAvailabilityLayerClient) Stop() error { - d.logger.Info("stopoing GRPC DALC") - return d.conn.Close() -} - -// SubmitBlocks proxies SubmitBlocks request to gRPC server. -func (d *DataAvailabilityLayerClient) SubmitBlocks(ctx context.Context, blocks []*types.Block) da.ResultSubmitBlocks { - bps := make([]*rollkit.Block, len(blocks)) - // convert blocks to protobuf - for i, block := range blocks { - bp, err := block.ToProto() - if err != nil { - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}, - } - } - bps[i] = bp - } - - resp, err := d.client.SubmitBlocks(ctx, &dalc.SubmitBlocksRequest{Blocks: bps}) - if err != nil { - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}, - } - } - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusCode(resp.Result.Code), - Message: resp.Result.Message, - DAHeight: resp.Result.DAHeight, - }, - } -} - -// RetrieveBlocks proxies RetrieveBlocks request to gRPC server. -func (d *DataAvailabilityLayerClient) RetrieveBlocks(ctx context.Context, daHeight uint64) da.ResultRetrieveBlocks { - resp, err := d.client.RetrieveBlocks(ctx, &dalc.RetrieveBlocksRequest{DAHeight: daHeight}) - if err != nil { - return da.ResultRetrieveBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}} - } - - blocks := make([]*types.Block, len(resp.Blocks)) - for i, block := range resp.Blocks { - var b types.Block - err = b.FromProto(block) - if err != nil { - return da.ResultRetrieveBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}} - } - blocks[i] = &b - } - return da.ResultRetrieveBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusCode(resp.Result.Code), - Message: resp.Result.Message, - DAHeight: daHeight, - }, - Blocks: blocks, - } -} diff --git a/da/grpc/mockserv/cmd/main.go b/da/grpc/mockserv/cmd/main.go deleted file mode 100644 index 2edfbb0a9a..0000000000 --- a/da/grpc/mockserv/cmd/main.go +++ /dev/null @@ -1,38 +0,0 @@ -package main - -import ( - "flag" - "log" - "net" - "os" - "strconv" - - cmlog "github.com/cometbft/cometbft/libs/log" - - grpcda "github.com/rollkit/rollkit/da/grpc" - "github.com/rollkit/rollkit/da/grpc/mockserv" - "github.com/rollkit/rollkit/store" -) - -func main() { - conf := grpcda.DefaultConfig - logger := cmlog.NewTMLogger(os.Stdout) - - flag.IntVar(&conf.Port, "port", conf.Port, "listening port") - flag.StringVar(&conf.Host, "host", "0.0.0.0", "listening address") - flag.Parse() - - kv, err := store.NewDefaultKVStore(".", "db", "rollkit") - if err != nil { - log.Panic(err) - } - lis, err := net.Listen("tcp", conf.Host+":"+strconv.Itoa(conf.Port)) - if err != nil { - log.Panic(err) - } - log.Println("Listening on:", lis.Addr()) - srv := mockserv.GetServer(kv, conf, nil, logger) - if err := srv.Serve(lis); err != nil { - log.Println("error while serving:", err) - } -} diff --git a/da/grpc/mockserv/mockserv.go b/da/grpc/mockserv/mockserv.go deleted file mode 100644 index 96809935be..0000000000 --- a/da/grpc/mockserv/mockserv.go +++ /dev/null @@ -1,78 +0,0 @@ -package mockserv - -import ( - "context" - - cmlog "github.com/cometbft/cometbft/libs/log" - ds "github.com/ipfs/go-datastore" - "google.golang.org/grpc" - - "github.com/rollkit/go-da/test" - grpcda "github.com/rollkit/rollkit/da/grpc" - "github.com/rollkit/rollkit/da/newda" - "github.com/rollkit/rollkit/types" - "github.com/rollkit/rollkit/types/pb/dalc" - "github.com/rollkit/rollkit/types/pb/rollkit" -) - -// GetServer creates and returns gRPC server instance. -func GetServer(kv ds.Datastore, conf grpcda.Config, mockConfig []byte, logger cmlog.Logger) *grpc.Server { - srv := grpc.NewServer() - mockImpl := &mockImpl{mock: &newda.NewDA{DA: test.NewDummyDA()}} - err := mockImpl.mock.Init([8]byte{}, mockConfig, kv, logger) - if err != nil { - logger.Error("failed to initialize mock DALC", "error", err) - panic(err) - } - err = mockImpl.mock.Start() - if err != nil { - logger.Error("failed to start mock DALC", "error", err) - panic(err) - } - dalc.RegisterDALCServiceServer(srv, mockImpl) - return srv -} - -type mockImpl struct { - mock *newda.NewDA -} - -func (m *mockImpl) SubmitBlocks(ctx context.Context, request *dalc.SubmitBlocksRequest) (*dalc.SubmitBlocksResponse, error) { - blocks := make([]*types.Block, len(request.Blocks)) - for i := range request.Blocks { - var b types.Block - err := b.FromProto(request.Blocks[i]) - if err != nil { - return nil, err - } - blocks[i] = &b - } - - resp := m.mock.SubmitBlocks(ctx, blocks) - return &dalc.SubmitBlocksResponse{ - Result: &dalc.DAResponse{ - Code: dalc.StatusCode(resp.Code), - Message: resp.Message, - DAHeight: resp.DAHeight, - }, - }, nil -} - -func (m *mockImpl) RetrieveBlocks(ctx context.Context, request *dalc.RetrieveBlocksRequest) (*dalc.RetrieveBlocksResponse, error) { - resp := m.mock.RetrieveBlocks(ctx, request.DAHeight) - blocks := make([]*rollkit.Block, len(resp.Blocks)) - for i := range resp.Blocks { - bp, err := resp.Blocks[i].ToProto() - if err != nil { - return nil, err - } - blocks[i] = bp - } - return &dalc.RetrieveBlocksResponse{ - Result: &dalc.DAResponse{ - Code: dalc.StatusCode(resp.Code), - Message: resp.Message, - }, - Blocks: blocks, - }, nil -} diff --git a/da/mock/main.go b/da/mock/main.go new file mode 100644 index 0000000000..12fb217077 --- /dev/null +++ b/da/mock/main.go @@ -0,0 +1,34 @@ +package main + +import ( + "flag" + "log" + "net" + "strconv" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + + "github.com/rollkit/go-da/proxy" + goDATest "github.com/rollkit/go-da/test" +) + +func main() { + var ( + host string + port int + ) + flag.IntVar(&port, "port", 7980, "listening port") + flag.StringVar(&host, "host", "0.0.0.0", "listening address") + flag.Parse() + + lis, err := net.Listen("tcp", host+":"+strconv.Itoa(port)) + if err != nil { + log.Panic(err) + } + log.Println("Listening on:", lis.Addr()) + srv := proxy.NewServer(goDATest.NewDummyDA(), grpc.Creds(insecure.NewCredentials())) + if err := srv.Serve(lis); err != nil { + log.Fatal("error while serving:", err) + } +} diff --git a/da/mock/mock.go b/da/mock/mock.go deleted file mode 100644 index 617b997736..0000000000 --- a/da/mock/mock.go +++ /dev/null @@ -1,229 +0,0 @@ -package mock - -import ( - "bytes" - "context" - "encoding/hex" - "fmt" - "math/rand" - "sync" - "sync/atomic" - "time" - - ds "github.com/ipfs/go-datastore" - - "github.com/rollkit/celestia-openrpc/types/core" - "github.com/rollkit/rollkit/da" - "github.com/rollkit/rollkit/store" - "github.com/rollkit/rollkit/third_party/log" - "github.com/rollkit/rollkit/types" -) - -// DataAvailabilityLayerClient is intended only for usage in tests. -// It does actually ensures DA - it stores data in-memory. -type DataAvailabilityLayerClient struct { - logger log.Logger - dalcKV ds.Datastore - - daHeaders map[uint64]*core.DataAvailabilityHeader - daHeadersLock sync.RWMutex - - daHeight uint64 - config config -} - -const defaultBlockTime = 3 * time.Second - -type config struct { - BlockTime time.Duration -} - -var _ da.DataAvailabilityLayerClient = &DataAvailabilityLayerClient{} -var _ da.BlockRetriever = &DataAvailabilityLayerClient{} - -// Init is called once to allow DA client to read configuration and initialize resources. -func (m *DataAvailabilityLayerClient) Init(_ types.NamespaceID, config []byte, dalcKV ds.Datastore, logger log.Logger) error { - m.logger = logger - m.dalcKV = dalcKV - m.daHeight = 1 - m.daHeaders = make(map[uint64]*core.DataAvailabilityHeader) - - eds, err := RandEDS(4) - if err != nil { - return err - } - dah, err := core.NewDataAvailabilityHeader(eds) - if err != nil { - return err - } - m.daHeadersLock.Lock() - m.daHeaders[m.daHeight] = &dah - m.daHeadersLock.Unlock() - - if len(config) > 0 { - var err error - m.config.BlockTime, err = time.ParseDuration(string(config)) - if err != nil { - return err - } - } else { - m.config.BlockTime = defaultBlockTime - } - return nil -} - -// Start implements DataAvailabilityLayerClient interface. -func (m *DataAvailabilityLayerClient) Start() error { - m.logger.Debug("Mock Data Availability Layer Client starting") - go func() { - // This infinite loop is expected to be stopped and cleaned up - // by the GC. This is OK because it is only a test helper and - // the block time is sufficiently long that there should not be - // a lot of wasted cycles. - for { - time.Sleep(m.config.BlockTime) - m.updateDAHeight() - } - }() - return nil -} - -// Stop implements DataAvailabilityLayerClient interface. -func (m *DataAvailabilityLayerClient) Stop() error { - m.logger.Debug("Mock Data Availability Layer Client stopped") - return nil -} - -// GetHeaderByHeight returns the header at the given height. -func (m *DataAvailabilityLayerClient) GetHeaderByHeight(height uint64) *core.DataAvailabilityHeader { - m.daHeadersLock.RLock() - dah := m.daHeaders[height] - m.daHeadersLock.RUnlock() - return dah -} - -func isEqual(headerA, headerB *core.DataAvailabilityHeader) bool { - if len(headerA.RowRoots) != len(headerB.RowRoots) { - return false - } - if len(headerA.ColumnRoots) != len(headerB.ColumnRoots) { - return false - } - for i, row := range headerA.RowRoots { - if !bytes.Equal(row, headerB.RowRoots[i]) { - return false - } - } - for i, col := range headerA.ColumnRoots { - if !bytes.Equal(col, headerB.ColumnRoots[i]) { - return false - } - } - return true -} - -// GetHeightByHeader returns the height for the given header. -func (m *DataAvailabilityLayerClient) GetHeightByHeader(dah *core.DataAvailabilityHeader) uint64 { - daHeight := atomic.LoadUint64(&m.daHeight) - for height := uint64(0); height < daHeight; height++ { - m.daHeadersLock.RLock() - header, ok := m.daHeaders[height] - m.daHeadersLock.RUnlock() - if !ok { - continue - } - if isEqual(header, dah) { - return height - } - } - return 0 -} - -// SubmitBlocks submits the passed in blocks to the DA layer. -// This should create a transaction which (potentially) -// triggers a state transition in the DA layer. -func (m *DataAvailabilityLayerClient) SubmitBlocks(ctx context.Context, blocks []*types.Block) da.ResultSubmitBlocks { - daHeight := atomic.LoadUint64(&m.daHeight) - - for _, block := range blocks { - blockHeight := uint64(block.Height()) - m.logger.Debug("Submitting blocks to DA layer!", "height", blockHeight, "dataLayerHeight", daHeight) - hash := block.Hash() - blob, err := block.MarshalBinary() - if err != nil { - return da.ResultSubmitBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}} - } - - err = m.dalcKV.Put(ctx, getKey(daHeight, blockHeight), hash[:]) - if err != nil { - return da.ResultSubmitBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}} - } - - err = m.dalcKV.Put(ctx, ds.NewKey(hex.EncodeToString(hash[:])), blob) - if err != nil { - return da.ResultSubmitBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}} - } - } - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusSuccess, - Message: "OK", - DAHeight: daHeight, - }, - } -} - -// RetrieveBlocks returns block at given height from data availability layer. -func (m *DataAvailabilityLayerClient) RetrieveBlocks(ctx context.Context, daHeight uint64) da.ResultRetrieveBlocks { - if daHeight >= atomic.LoadUint64(&m.daHeight) { - return da.ResultRetrieveBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: "block not found"}} - } - - results, err := store.PrefixEntries(ctx, m.dalcKV, getPrefix(daHeight)) - if err != nil { - return da.ResultRetrieveBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}} - } - - var blocks []*types.Block - for result := range results.Next() { - blob, err := m.dalcKV.Get(ctx, ds.NewKey(hex.EncodeToString(result.Entry.Value))) - if err != nil { - return da.ResultRetrieveBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}} - } - - block := &types.Block{} - err = block.UnmarshalBinary(blob) - if err != nil { - return da.ResultRetrieveBlocks{BaseResult: da.BaseResult{Code: da.StatusError, Message: err.Error()}} - } - blocks = append(blocks, block) - } - - return da.ResultRetrieveBlocks{BaseResult: da.BaseResult{Code: da.StatusSuccess}, Blocks: blocks} -} - -func getPrefix(daHeight uint64) string { - return store.GenerateKey([]interface{}{daHeight}) -} - -func getKey(daHeight uint64, height uint64) ds.Key { - return ds.NewKey(store.GenerateKey([]interface{}{daHeight, height})) -} - -func (m *DataAvailabilityLayerClient) updateDAHeight() { - blockStep := rand.Uint64()%10 + 1 //nolint:gosec - atomic.AddUint64(&m.daHeight, blockStep) - eds, err := RandEDS(4) - if err != nil { - fmt.Println(err) - return - } - dah, err := core.NewDataAvailabilityHeader(eds) - if err != nil { - fmt.Println(err) - return - } - m.daHeadersLock.Lock() - m.daHeaders[atomic.LoadUint64(&m.daHeight)] = &dah - defer m.daHeadersLock.Unlock() -} diff --git a/da/mock/util.go b/da/mock/util.go deleted file mode 100644 index e2a454ae58..0000000000 --- a/da/mock/util.go +++ /dev/null @@ -1,191 +0,0 @@ -package mock - -import ( - "bytes" - "fmt" - "math/rand" - "sort" - "time" - - "github.com/celestiaorg/nmt" - "github.com/celestiaorg/rsmt2d" - - "github.com/rollkit/celestia-openrpc/types/appconsts" - "github.com/rollkit/celestia-openrpc/types/namespace" - "github.com/rollkit/celestia-openrpc/types/share" -) - -// Fulfills the rsmt2d.Tree interface and rsmt2d.TreeConstructorFn function -var ( - _ rsmt2d.TreeConstructorFn = NewConstructor(0) - _ rsmt2d.Tree = &ErasuredNamespacedMerkleTree{} -) - -// ErasuredNamespacedMerkleTree wraps NamespaceMerkleTree to conform to the -// rsmt2d.Tree interface while also providing the correct namespaces to the -// underlying NamespaceMerkleTree. It does this by adding the already included -// namespace to the first half of the tree, and then uses the parity namespace -// ID for each share pushed to the second half of the tree. This allows for the -// namespaces to be included in the erasure data, while also keeping the nmt -// library sufficiently general -type ErasuredNamespacedMerkleTree struct { - squareSize uint64 // note: this refers to the width of the original square before erasure-coded - options []nmt.Option - tree *nmt.NamespacedMerkleTree - // axisIndex is the index of the axis (row or column) that this tree is on. This is passed - // by rsmt2d and used to help determine which quadrant each leaf belongs to. - axisIndex uint64 - // shareIndex is the index of the share in a row or column that is being - // pushed to the tree. It is expected to be in the range: 0 <= shareIndex < - // 2*squareSize. shareIndex is used to help determine which quadrant each - // leaf belongs to, along with keeping track of how many leaves have been - // added to the tree so far. - shareIndex uint64 -} - -// NewErasuredNamespacedMerkleTree creates a new ErasuredNamespacedMerkleTree -// with an underlying NMT of namespace size `namespace.NamespaceSize` and with -// `ignoreMaxNamespace=true`. axisIndex is the index of the row or column that -// this tree is committing to. squareSize must be greater than zero. -func NewErasuredNamespacedMerkleTree(squareSize uint64, axisIndex uint, options ...nmt.Option) ErasuredNamespacedMerkleTree { - if squareSize == 0 { - panic("cannot create a ErasuredNamespacedMerkleTree of squareSize == 0") - } - options = append(options, nmt.NamespaceIDSize(namespace.NamespaceSize)) - options = append(options, nmt.IgnoreMaxNamespace(true)) - tree := nmt.New(namespace.NewBaseHashFunc(), options...) - return ErasuredNamespacedMerkleTree{squareSize: squareSize, options: options, tree: tree, axisIndex: uint64(axisIndex), shareIndex: 0} -} - -type constructor struct { - squareSize uint64 - opts []nmt.Option -} - -// NewConstructor creates a tree constructor function as required by rsmt2d to -// calculate the data root. It creates that tree using the -// wrapper.ErasuredNamespacedMerkleTree. -func NewConstructor(squareSize uint64, opts ...nmt.Option) rsmt2d.TreeConstructorFn { - return constructor{ - squareSize: squareSize, - opts: opts, - }.NewTree -} - -// NewTree creates a new rsmt2d.Tree using the -// wrapper.ErasuredNamespacedMerkleTree with predefined square size and -// nmt.Options -func (c constructor) NewTree(_ rsmt2d.Axis, axisIndex uint) rsmt2d.Tree { - newTree := NewErasuredNamespacedMerkleTree(c.squareSize, axisIndex, c.opts...) - return &newTree -} - -// Push adds the provided data to the underlying NamespaceMerkleTree, and -// automatically uses the first DefaultNamespaceIDLen number of bytes as the -// namespace unless the data pushed to the second half of the tree. Fulfills the -// rsmt.Tree interface. NOTE: panics if an error is encountered while pushing or -// if the tree size is exceeded. -func (w *ErasuredNamespacedMerkleTree) Push(data []byte) error { - if w.axisIndex+1 > 2*w.squareSize || w.shareIndex+1 > 2*w.squareSize { - return fmt.Errorf("pushed past predetermined square size: boundary at %d index at %d %d", 2*w.squareSize, w.axisIndex, w.shareIndex) - } - if len(data) < namespace.NamespaceSize { - return fmt.Errorf("data is too short to contain namespace ID") - } - nidAndData := make([]byte, namespace.NamespaceSize+len(data)) - copy(nidAndData[namespace.NamespaceSize:], data) - // use the parity namespace if the cell is not in Q0 of the extended data square - if w.isQuadrantZero() { - copy(nidAndData[:namespace.NamespaceSize], data[:namespace.NamespaceSize]) - } else { - copy(nidAndData[:namespace.NamespaceSize], namespace.ParitySharesNamespace.Bytes()) - } - err := w.tree.Push(nidAndData) - if err != nil { - return err - } - w.incrementShareIndex() - return nil -} - -// Root fulfills the rsmt.Tree interface by generating and returning the -// underlying NamespaceMerkleTree Root. -func (w *ErasuredNamespacedMerkleTree) Root() ([]byte, error) { - root, err := w.tree.Root() - if err != nil { - return nil, err - } - return root, nil -} - -// ProveRange returns a Merkle range proof for the leaf range [start, end] where `end` is non-inclusive. -func (w *ErasuredNamespacedMerkleTree) ProveRange(start, end int) (nmt.Proof, error) { - return w.tree.ProveRange(start, end) -} - -// incrementShareIndex increments the share index by one. -func (w *ErasuredNamespacedMerkleTree) incrementShareIndex() { - w.shareIndex++ -} - -// isQuadrantZero returns true if the current share index and axis index are both -// in the original data square. -func (w *ErasuredNamespacedMerkleTree) isQuadrantZero() bool { - return w.shareIndex < w.squareSize && w.axisIndex < w.squareSize -} - -// RandEDS generates EDS filled with the random data with the given size for original square. It -// uses require.TestingT to be able to take both a *testing.T and a *testing.B. -func RandEDS(size int) (*rsmt2d.ExtendedDataSquare, error) { - shares, err := RandShares(size * size) - if err != nil { - return nil, err - } - // recompute the eds - return rsmt2d.ComputeExtendedDataSquare(share.ToBytes(shares), share.DefaultRSMT2DCodec(), NewConstructor(uint64(size))) -} - -// RandShares generate 'total' amount of shares filled with random data. It uses require.TestingT -// to be able to take both a *testing.T and a *testing.B. -func RandShares(total int) ([]share.Share, error) { - if total&(total-1) != 0 { - return nil, fmt.Errorf("total must be power of 2: %d", total) - } - - var r = rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec - shares := make([]share.Share, total) - for i := range shares { - shr := make([]byte, appconsts.ShareSize) - copy(shr[:appconsts.NamespaceSize], RandNamespace()) - _, err := r.Read(shr[appconsts.NamespaceSize:]) - if err != nil { - return nil, err - } - share, err := share.NewShare(shr) - if err != nil { - return nil, err - } - shares[i] = *share - } - sort.Slice(shares, func(i, j int) bool { return bytes.Compare(shares[i].ToBytes(), shares[j].ToBytes()) < 0 }) - - return shares, nil -} - -// RandNamespace generates random valid data namespace for testing purposes. -func RandNamespace() share.Namespace { - var r = rand.New(rand.NewSource(time.Now().UnixNano())) //nolint:gosec - rb := make([]byte, namespace.NamespaceVersionZeroIDSize) - r.Read(rb) // nolint:gosec - for { - // This infinite loop is here to ensure that we generate a valid - // namespace for testing. We don't care about errors from - // invalid namespaces and the chances of this loop firing a - // large number of times is very low. - namespace, _ := share.NewBlobNamespaceV0(rb) - if err := namespace.ValidateForData(); err != nil { - continue - } - return namespace - } -} diff --git a/da/newda/newda.go b/da/newda/newda.go deleted file mode 100644 index 5ba44b95e6..0000000000 --- a/da/newda/newda.go +++ /dev/null @@ -1,125 +0,0 @@ -package newda - -import ( - "context" - "encoding/binary" - "fmt" - - pb "github.com/rollkit/rollkit/types/pb/rollkit" - - "github.com/gogo/protobuf/proto" - ds "github.com/ipfs/go-datastore" - - newda "github.com/rollkit/go-da" - "github.com/rollkit/rollkit/da" - "github.com/rollkit/rollkit/third_party/log" - "github.com/rollkit/rollkit/types" -) - -// NewDA is a new DA implementation. -type NewDA struct { - DA newda.DA - logger log.Logger -} - -// Init is called once to allow DA client to read configuration and initialize resources. -func (n *NewDA) Init(namespaceID types.NamespaceID, config []byte, kvStore ds.Datastore, logger log.Logger) error { - n.logger = logger - return nil -} - -// Start creates connection to gRPC server and instantiates gRPC client. -func (n *NewDA) Start() error { - return nil -} - -// Stop closes connection to gRPC server. -func (n *NewDA) Stop() error { - return nil -} - -// SubmitBlocks submits blocks to DA. -func (n *NewDA) SubmitBlocks(ctx context.Context, blocks []*types.Block) da.ResultSubmitBlocks { - blobs := make([][]byte, len(blocks)) - for i := range blocks { - blob, err := blocks[i].MarshalBinary() - if err != nil { - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: "failed to serialize block", - }, - } - } - blobs[i] = blob - } - ids, _, err := n.DA.Submit(blobs) - if err != nil { - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: "failed to submit blocks: " + err.Error(), - }, - } - } - - return da.ResultSubmitBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusSuccess, - DAHeight: binary.LittleEndian.Uint64(ids[0]), - }, - } -} - -// RetrieveBlocks retrieves blocks from DA. -func (n *NewDA) RetrieveBlocks(ctx context.Context, dataLayerHeight uint64) da.ResultRetrieveBlocks { - ids, err := n.DA.GetIDs(dataLayerHeight) - if err != nil { - return da.ResultRetrieveBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: fmt.Sprintf("failed to get IDs: %s", err.Error()), - DAHeight: dataLayerHeight, - }, - } - } - - blobs, err := n.DA.Get(ids) - if err != nil { - return da.ResultRetrieveBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: fmt.Sprintf("failed to get blobs: %s", err.Error()), - DAHeight: dataLayerHeight, - }, - } - } - - blocks := make([]*types.Block, len(blobs)) - for i, blob := range blobs { - var block pb.Block - err = proto.Unmarshal(blob, &block) - if err != nil { - n.logger.Error("failed to unmarshal block", "daHeight", dataLayerHeight, "position", i, "error", err) - continue - } - blocks[i] = new(types.Block) - err := blocks[i].FromProto(&block) - if err != nil { - return da.ResultRetrieveBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusError, - Message: err.Error(), - }, - } - } - } - - return da.ResultRetrieveBlocks{ - BaseResult: da.BaseResult{ - Code: da.StatusSuccess, - DAHeight: dataLayerHeight, - }, - Blocks: blocks, - } -} diff --git a/da/registry/registry.go b/da/registry/registry.go deleted file mode 100644 index 10f251103c..0000000000 --- a/da/registry/registry.go +++ /dev/null @@ -1,61 +0,0 @@ -package registry - -import ( - "fmt" - - "github.com/rollkit/go-da/test" - "github.com/rollkit/rollkit/da/newda" - - "github.com/rollkit/rollkit/da" - "github.com/rollkit/rollkit/da/celestia" - "github.com/rollkit/rollkit/da/grpc" -) - -// ErrAlreadyRegistered is used when user tries to register DA using a name already used in registry. -type ErrAlreadyRegistered struct { - name string -} - -func (e *ErrAlreadyRegistered) Error() string { - return fmt.Sprintf("Data Availability Layer '%s' already registered", e.name) -} - -// this is a central registry for all Data Availability Layer Clients -var clients = map[string]func() da.DataAvailabilityLayerClient{ - "grpc": func() da.DataAvailabilityLayerClient { return &grpc.DataAvailabilityLayerClient{} }, - "celestia": func() da.DataAvailabilityLayerClient { return &celestia.DataAvailabilityLayerClient{} }, - "newda": func() da.DataAvailabilityLayerClient { - return &newda.NewDA{ - DA: test.NewDummyDA(), - } - }, -} - -// GetClient returns client identified by name. -func GetClient(name string) da.DataAvailabilityLayerClient { - f, ok := clients[name] - if !ok { - return nil - } - return f() -} - -// Register adds a Data Availability Layer Client to registry. -// -// If name was previously used in the registry, error is returned. -func Register(name string, constructor func() da.DataAvailabilityLayerClient) error { - if _, found := clients[name]; !found { - clients[name] = constructor - return nil - } - return &ErrAlreadyRegistered{name: name} -} - -// RegisteredClients returns names of all DA clients in registry. -func RegisteredClients() []string { - registered := make([]string, 0, len(clients)) - for name := range clients { - registered = append(registered, name) - } - return registered -} diff --git a/da/registry/registry_test.go b/da/registry/registry_test.go deleted file mode 100644 index 856d51f603..0000000000 --- a/da/registry/registry_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package registry - -import ( - "testing" - - "github.com/stretchr/testify/assert" - - "github.com/rollkit/go-da/test" - "github.com/rollkit/rollkit/da" - "github.com/rollkit/rollkit/da/newda" -) - -func TestRegistry(t *testing.T) { - assert := assert.New(t) - - expected := []string{"grpc", "celestia", "newda"} - actual := RegisteredClients() - - assert.ElementsMatch(expected, actual) - - constructor := func() da.DataAvailabilityLayerClient { - return &newda.NewDA{DA: test.NewDummyDA()} // cheating, only for tests :D - } - err := Register("testDA", constructor) - assert.NoError(err) - - // re-registration should fail - err = Register("celestia", constructor) - regErr := &ErrAlreadyRegistered{} - assert.ErrorAs(err, ®Err) - assert.Equal("celestia", regErr.name) - - assert.Contains(RegisteredClients(), "testDA") - - for _, e := range RegisteredClients() { - dalc := GetClient(e) - assert.NotNil(dalc) - } - - assert.Nil(GetClient("nonexistent")) -} diff --git a/da/test/da_test.go b/da/test/da_test.go deleted file mode 100644 index 399635ead2..0000000000 --- a/da/test/da_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package test - -import ( - "context" - "encoding/json" - "fmt" - "math/rand" - "net" - "os" - "strconv" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - "google.golang.org/grpc" - - cmlog "github.com/cometbft/cometbft/libs/log" - - "github.com/rollkit/rollkit/da" - "github.com/rollkit/rollkit/da/celestia" - cmock "github.com/rollkit/rollkit/da/celestia/mock" - grpcda "github.com/rollkit/rollkit/da/grpc" - "github.com/rollkit/rollkit/da/grpc/mockserv" - "github.com/rollkit/rollkit/da/newda" - "github.com/rollkit/rollkit/da/registry" - "github.com/rollkit/rollkit/store" - test "github.com/rollkit/rollkit/test/log" - "github.com/rollkit/rollkit/types" -) - -const mockDaBlockTime = 100 * time.Millisecond - -var ( - testNamespaceID = types.NamespaceID{0, 1, 2, 3, 4, 5, 6, 7} - - testConfig = celestia.Config{ - Timeout: 15 * time.Second, - GasLimit: 3000000, - } -) - -func TestMain(m *testing.M) { - srv := startMockGRPCServ() - if srv == nil { - os.Exit(1) - } - - httpServer := startMockCelestiaNodeServer() - if httpServer == nil { - os.Exit(1) - } - - exitCode := m.Run() - - // teardown servers - srv.GracefulStop() - httpServer.Stop() - - os.Exit(exitCode) -} - -func TestLifecycle(t *testing.T) { - for _, dalc := range registry.RegisteredClients() { - t.Run(dalc, func(t *testing.T) { - doTestLifecycle(t, registry.GetClient(dalc)) - }) - } -} - -func doTestLifecycle(t *testing.T, dalc da.DataAvailabilityLayerClient) { - require := require.New(t) - - conf := []byte{} - if _, ok := dalc.(*newda.NewDA); ok { - conf = []byte(mockDaBlockTime.String()) - } - if _, ok := dalc.(*celestia.DataAvailabilityLayerClient); ok { - conf, _ = json.Marshal(testConfig) - } - err := dalc.Init(testNamespaceID, conf, nil, test.NewFileLoggerCustom(t, test.TempLogFileName(t, "dalc"))) - require.NoError(err) - - err = dalc.Start() - require.NoError(err) - - defer func() { - require.NoError(dalc.Stop()) - }() -} - -func TestRetrieve(t *testing.T) { - for _, client := range registry.RegisteredClients() { - t.Run(client, func(t *testing.T) { - dalc := registry.GetClient(client) - _, ok := dalc.(da.BlockRetriever) - if ok { - doTestRetrieve(t, dalc) - } - }) - } -} - -func startMockGRPCServ() *grpc.Server { - conf := grpcda.DefaultConfig - logger := cmlog.NewTMLogger(os.Stdout) - - kvStore, _ := store.NewDefaultInMemoryKVStore() - srv := mockserv.GetServer(kvStore, conf, []byte(mockDaBlockTime.String()), logger) - lis, err := net.Listen("tcp", conf.Host+":"+strconv.Itoa(conf.Port)) - if err != nil { - fmt.Println(err) - return nil - } - go func() { - _ = srv.Serve(lis) - }() - return srv -} - -func startMockCelestiaNodeServer() *cmock.Server { - httpSrv := cmock.NewServer(mockDaBlockTime, cmlog.NewTMLogger(os.Stdout)) - url, err := httpSrv.Start() - if err != nil { - fmt.Println("can't start mock celestia-node RPC server") - return nil - } - testConfig.BaseURL = url - return httpSrv -} - -func doTestRetrieve(t *testing.T, dalc da.DataAvailabilityLayerClient) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - require := require.New(t) - assert := assert.New(t) - - // mock DALC will advance block height every 100ms - conf := []byte{} - if _, ok := dalc.(*newda.NewDA); ok { - conf = []byte(mockDaBlockTime.String()) - } - if _, ok := dalc.(*celestia.DataAvailabilityLayerClient); ok { - conf, _ = json.Marshal(testConfig) - } - kvStore, _ := store.NewDefaultInMemoryKVStore() - err := dalc.Init(testNamespaceID, conf, kvStore, test.NewFileLoggerCustom(t, test.TempLogFileName(t, "dalc"))) - require.NoError(err) - - err = dalc.Start() - require.NoError(err) - defer func() { - require.NoError(dalc.Stop()) - }() - - // wait a bit more than mockDaBlockTime, so mock can "produce" some blocks - time.Sleep(mockDaBlockTime + 20*time.Millisecond) - - retriever := dalc.(da.BlockRetriever) - countAtHeight := make(map[uint64]int) - blockToDAHeight := make(map[*types.Block]uint64) - numBatches := uint64(10) - blocksSubmittedPerBatch := 10 - - for i := uint64(0); i < numBatches; i++ { - blocks := make([]*types.Block, blocksSubmittedPerBatch) - for j := 0; j < len(blocks); j++ { - blocks[j] = types.GetRandomBlock(i*numBatches+uint64(j), rand.Int()%20) //nolint:gosec - } - resp := dalc.SubmitBlocks(ctx, blocks) - assert.Equal(da.StatusSuccess, resp.Code, resp.Message) - time.Sleep(time.Duration(rand.Int63() % mockDaBlockTime.Milliseconds())) //nolint:gosec - - for _, b := range blocks { - blockToDAHeight[b] = resp.DAHeight - countAtHeight[resp.DAHeight]++ - } - } - - // wait a bit more than mockDaBlockTime, so mock can "produce" last blocks - time.Sleep(mockDaBlockTime + 20*time.Millisecond) - - for h, cnt := range countAtHeight { - t.Log("Retrieving block, DA Height", h) - ret := retriever.RetrieveBlocks(ctx, h) - assert.Equal(da.StatusSuccess, ret.Code, ret.Message) - require.NotEmpty(ret.Blocks, h) - assert.Equal(cnt%blocksSubmittedPerBatch, 0) - assert.Len(ret.Blocks, cnt, h) - } - - for b, h := range blockToDAHeight { - ret := retriever.RetrieveBlocks(ctx, h) - assert.Equal(da.StatusSuccess, ret.Code, h) - require.NotEmpty(ret.Blocks, h) - assert.Contains(ret.Blocks, b, h) - } -} diff --git a/go.mod b/go.mod index 8f645043bd..ccd7a5d5a3 100644 --- a/go.mod +++ b/go.mod @@ -4,15 +4,12 @@ go 1.20 require ( github.com/celestiaorg/go-header v0.4.1 - github.com/celestiaorg/nmt v0.20.0 - github.com/celestiaorg/rsmt2d v0.11.0 github.com/celestiaorg/utils v0.1.0 github.com/cometbft/cometbft v0.37.2 github.com/creachadair/taskgroup v0.6.2 github.com/dgraph-io/badger/v3 v3.2103.5 github.com/go-kit/kit v0.13.0 github.com/gogo/protobuf v1.3.3 - github.com/gorilla/mux v1.8.1 github.com/gorilla/rpc v1.2.1 github.com/gorilla/websocket v1.5.1 github.com/ipfs/go-datastore v0.6.0 @@ -23,7 +20,6 @@ require ( github.com/libp2p/go-libp2p-pubsub v0.9.3 github.com/multiformats/go-multiaddr v0.12.0 github.com/prometheus/client_golang v1.17.0 - github.com/rollkit/celestia-openrpc v0.3.0 github.com/rollkit/go-da v0.0.0-20231117151938-ee3b613d7a3a github.com/rs/cors v1.10.1 github.com/spf13/cobra v1.8.0 @@ -37,14 +33,11 @@ require ( ) require ( - cosmossdk.io/math v1.1.2 // indirect github.com/benbjohnson/clock v1.3.5 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect github.com/btcsuite/btcd/chaincfg/chainhash v1.0.2 // indirect - github.com/celestiaorg/go-fraud v0.2.0 // indirect github.com/celestiaorg/go-libp2p-messenger v0.2.0 // indirect - github.com/celestiaorg/merkletree v0.0.0-20210714075610-a84dc3ddbbe4 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/cometbft/cometbft-db v0.8.0 // indirect @@ -61,7 +54,6 @@ require ( github.com/docker/go-units v0.5.0 // indirect github.com/dustin/go-humanize v1.0.0 // indirect github.com/elastic/gosigar v0.14.2 // indirect - github.com/filecoin-project/go-jsonrpc v0.3.1 // indirect github.com/flynn/noise v1.0.0 // indirect github.com/francoispqt/gojay v1.2.13 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect @@ -102,7 +94,6 @@ require ( github.com/jmhodges/levigo v1.0.0 // indirect github.com/klauspost/compress v1.17.0 // indirect github.com/klauspost/cpuid/v2 v2.2.5 // indirect - github.com/klauspost/reedsolomon v1.11.8 // indirect github.com/koron/go-ssdp v0.0.4 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect github.com/libp2p/go-cidranger v1.1.0 // indirect @@ -153,6 +144,7 @@ require ( github.com/quic-go/quic-go v0.37.6 // indirect github.com/quic-go/webtransport-go v0.5.3 // indirect github.com/raulk/go-watchdog v1.3.0 // indirect + github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/sagikazarmark/locafero v0.3.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect @@ -180,7 +172,6 @@ require ( golang.org/x/sys v0.15.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/tools v0.14.0 // indirect - golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect gonum.org/v1/gonum v0.11.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20230920204549-e6e6cdab5c13 // indirect gopkg.in/ini.v1 v1.67.0 // indirect diff --git a/go.sum b/go.sum index 1149f20677..9a6bb6d7c5 100644 --- a/go.sum +++ b/go.sum @@ -62,8 +62,6 @@ cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RX cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= contrib.go.opencensus.io/exporter/stackdriver v0.13.4/go.mod h1:aXENhDJ1Y4lIg4EUaVTwzvYETVNZk10Pu26tevFKLUc= -cosmossdk.io/math v1.1.2 h1:ORZetZCTyWkI5GlZ6CZS28fMHi83ZYf+A2vVnHNzZBM= -cosmossdk.io/math v1.1.2/go.mod h1:l2Gnda87F0su8a/7FEKJfFdJrM0JZRXQaohlgJeyQh0= dmitri.shuralyov.com/app/changes v0.0.0-20180602232624-0a106ad413e3/go.mod h1:Yl+fi1br7+Rr3LqpNJf1/uxUdtRUV+Tnj0o93V2B9MU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= dmitri.shuralyov.com/html/belt v0.0.0-20180602232347-f7d459c86be0/go.mod h1:JLBrvjyP0v+ecvNYvCpyZgu5/xkfAUhi6wJj28eUfSU= @@ -78,7 +76,6 @@ github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.11.0/go.mod h1:HcM1YX14R7CJc github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= -github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.4.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= @@ -98,8 +95,6 @@ github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF0 github.com/Masterminds/sprig v2.15.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Masterminds/sprig v2.22.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY= -github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= -github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= @@ -191,25 +186,15 @@ github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23/go.mod h1:bbYlZJ7 github.com/butuzov/ireturn v0.1.1/go.mod h1:Wh6Zl3IMtTpaIKbmwzqi6olnM9ptYQxxVacMsOEFPoc= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= github.com/casbin/casbin/v2 v2.37.0/go.mod h1:vByNa/Fchek0KZUgG5wEsl7iFsiviAYKRtgrQfcJqHg= -github.com/celestiaorg/go-fraud v0.2.0 h1:aaq2JiW0gTnhEdac3l51UCqSyJ4+VjFGTTpN83V4q7I= -github.com/celestiaorg/go-fraud v0.2.0/go.mod h1:lNY1i4K6kUeeE60Z2VK8WXd+qXb8KRzfBhvwPkK6aUc= github.com/celestiaorg/go-header v0.4.1 h1:bjbUcKDnhrJJ9EoE7vtPpgleNLVjc2S+cB4/qe8nQmo= github.com/celestiaorg/go-header v0.4.1/go.mod h1:H8xhnDLDLbkpwmWPhCaZyTnIV3dlVxBHPnxNXS2Qu6c= github.com/celestiaorg/go-libp2p-messenger v0.2.0 h1:/0MuPDcFamQMbw9xTZ73yImqgTO3jHV7wKHvWD/Irao= github.com/celestiaorg/go-libp2p-messenger v0.2.0/go.mod h1:s9PIhMi7ApOauIsfBcQwbr7m+HBzmVfDIS+QLdgzDSo= -github.com/celestiaorg/merkletree v0.0.0-20210714075610-a84dc3ddbbe4 h1:CJdIpo8n5MFP2MwK0gSRcOVlDlFdQJO1p+FqdxYzmvc= -github.com/celestiaorg/merkletree v0.0.0-20210714075610-a84dc3ddbbe4/go.mod h1:fzuHnhzj1pUygGz+1ZkB3uQbEUL4htqCGJ4Qs2LwMZA= -github.com/celestiaorg/nmt v0.20.0 h1:9i7ultZ8Wv5ytt8ZRaxKQ5KOOMo4A2K2T/aPGjIlSas= -github.com/celestiaorg/nmt v0.20.0/go.mod h1:Oz15Ub6YPez9uJV0heoU4WpFctxazuIhKyUtaYNio7E= -github.com/celestiaorg/rsmt2d v0.11.0 h1:lcto/637WyTEZR3dLRoNvyuExfnUbxvdvKi3qz/2V4k= -github.com/celestiaorg/rsmt2d v0.11.0/go.mod h1:6Y580I3gVr0+OVFfW6m2JTwnCCmvW3WfbwSLfuT+HCA= github.com/celestiaorg/utils v0.1.0 h1:WsP3O8jF7jKRgLNFmlDCwdThwOFMFxg0MnqhkLFVxPo= github.com/celestiaorg/utils v0.1.0/go.mod h1:vQTh7MHnvpIeCQZ2/Ph+w7K1R2UerDheZbgJEJD2hSU= -github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM= github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= -github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= @@ -255,7 +240,6 @@ github.com/containerd/cgroups v1.1.0 h1:v8rEWFl6EoqHB+swVNjVoCJE8o3jX7e8nqBGPLaD github.com/containerd/cgroups v1.1.0/go.mod h1:6ppBcbh/NOOUU+dMKrykgaBnK9lCIBxHqJDGwsa1mIw= github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= github.com/containerd/continuity v0.3.0/go.mod h1:wJEAIwKOm/pBZuBd0JmeTvnLquTB1Ag8espWhkykbPM= -github.com/containerd/continuity v0.4.1 h1:wQnVrjIyQ8vhU2sgOiL5T07jo+ouqc2bnKsv5/EqGhU= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= @@ -323,11 +307,8 @@ github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUn github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= github.com/docker/cli v20.10.14+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/cli v20.10.17+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= -github.com/docker/cli v24.0.2+incompatible h1:QdqR7znue1mtkXIJ+ruQMGQhpw2JzMJLRXp6zpzF6tM= github.com/docker/docker v20.10.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker v20.10.17+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= -github.com/docker/docker v24.0.2+incompatible h1:eATx+oLz9WdNVkQrr0qjQ8HvRJ4bOOxfzEo8R+dA3cg= -github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= @@ -367,8 +348,6 @@ github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGE github.com/fatih/color v1.12.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94= -github.com/filecoin-project/go-jsonrpc v0.3.1 h1:qwvAUc5VwAkooquKJmfz9R2+F8znhiqcNHYjEp/NM10= -github.com/filecoin-project/go-jsonrpc v0.3.1/go.mod h1:jBSvPTl8V1N7gSTuCR4bis8wnQnIjHbRPpROol6iQKM= github.com/firefart/nonamedreturns v1.0.4/go.mod h1:TDhe/tjI1BXo48CmYbUduTV7BdIga8MAO/xbKdcVsGI= github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/flynn/noise v1.0.0 h1:DlTHqmzmvcEiKj+4RYo/imoswx/4r6iBlCMfVtrMXpQ= @@ -536,7 +515,6 @@ github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeN github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gopacket v1.1.17/go.mod h1:UdDNZ1OO62aGYVnPhxT1U6aI7ukYtA/kB8vaU0diBUM= github.com/google/gopacket v1.1.19 h1:ves8RnFZPGiFnTS0uPQStjwru6uO6h+nlr9j6fL7kF8= github.com/google/gopacket v1.1.19/go.mod h1:iJ8V8n6KS+z2U1A8pUwu8bW5SyEMkXJB8Yo/Vo+TKTo= @@ -566,7 +544,6 @@ github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20230817174616-7a8ec2ada47b h1:h9U78+dx9a4BKdQkBBos92HalKpaGKHrp+3Uo6yTodo= github.com/google/pprof v0.0.0-20230817174616-7a8ec2ada47b/go.mod h1:czg5+yv1E0ZGTi6S6vVK1mke0fV+FaUhNGcd6VRS9Ik= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= github.com/google/trillian v1.3.11/go.mod h1:0tPraVHrSDkA3BO6vKX67zgLXs6SsOAbHEivX+9mPgw= github.com/google/uuid v0.0.0-20161128191214-064e2069ce9c/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -597,8 +574,6 @@ github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51 github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= -github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= -github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= github.com/gorilla/rpc v1.2.1 h1:yC+LMV5esttgpVvNORL/xX4jvTTEUE30UZhZ5JF7K9k= github.com/gorilla/rpc v1.2.1/go.mod h1:uNpOihAlF5xRFLuTYhfR0yfCTm0WTQSQttkMSptRfGk= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= @@ -707,7 +682,6 @@ github.com/imdario/mergo v0.3.4/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJ github.com/imdario/mergo v0.3.8/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/imdario/mergo v0.3.13/go.mod h1:4lJ1jqUDcsbIECGy0RUJAXNIhg+6ocWgb1ALK2O4oXg= -github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= @@ -814,8 +788,6 @@ github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuOb github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg= github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/klauspost/pgzip v1.2.5/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= -github.com/klauspost/reedsolomon v1.11.8 h1:s8RpUW5TK4hjr+djiOpbZJB4ksx+TdYbRH7vHQpwPOY= -github.com/klauspost/reedsolomon v1.11.8/go.mod h1:4bXRN+cVzMdml6ti7qLouuYi32KHJ5MGv0Qd8a47h6A= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -1079,7 +1051,6 @@ github.com/mitchellh/reflectwalk v1.0.1/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx github.com/moby/sys/mountinfo v0.5.0/go.mod h1:3bMD3Rg+zkqx8MRYPi7Pyb0Ie97QEBmdxbhnCLlSvSU= github.com/moby/term v0.0.0-20201216013528-df9cb8a40635/go.mod h1:FBS0z0QWA44HXygs7VXDUOGoN/1TV3RuWkLO04am3wc= github.com/moby/term v0.0.0-20210619224110-3f7ff695adc6/go.mod h1:E2VnQOmVuvZB6UYnnDB0qG5Nq/1tD9acaOpo6xmt0Kw= -github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= @@ -1211,13 +1182,10 @@ github.com/onsi/gomega v1.17.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAl github.com/onsi/gomega v1.19.0/go.mod h1:LY+I3pBVzYsTBU1AnDwOSxaYi9WoWiqgwooUqq9yPro= github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= -github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= -github.com/opencontainers/image-spec v1.1.0-rc2 h1:2zx/Stx4Wc5pIPDvIxHXvXtQFW/7XWJGmnM7r3wg034= github.com/opencontainers/runc v1.1.2/go.mod h1:Tj1hFw6eFWp/o33uxGf5yF2BX5yz2Z6iptFpuvbbKqc= github.com/opencontainers/runc v1.1.3/go.mod h1:1J5XiS+vdZ3wCyZybsuxXZWGrgSr8fFJHLXuG2PsnNg= -github.com/opencontainers/runc v1.1.7 h1:y2EZDS8sNng4Ksf0GUYNhKbTShZJPJg1FiXJNH/uoCk= github.com/opencontainers/runtime-spec v1.0.2/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/opencontainers/runtime-spec v1.1.0 h1:HHUyrt9mwHUjtasSbXSMvs4cyFxh+Bll4AjJ9odEGpg= @@ -1235,10 +1203,8 @@ github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJ github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= github.com/openzipkin/zipkin-go v0.2.5/go.mod h1:KpXfKdgRDnnhsxw4pNIH9Md5lyFqKUa4YDFlwRYAMyE= -github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4Emza6EbVUUGA= github.com/ory/dockertest v3.3.5+incompatible/go.mod h1:1vX4m9wsvi00u5bseYwXaSnhNrne+V0E6LAcBILJdPs= github.com/ory/dockertest/v3 v3.9.1/go.mod h1:42Ir9hmvaAPm0Mgibk6mBPi7SFvTXxEcnztDYOJ//uM= -github.com/ory/dockertest/v3 v3.10.0 h1:4K3z2VMe8Woe++invjaTB7VRyQXQy5UY+loujO4aNE4= github.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw= github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= @@ -1375,8 +1341,7 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.1/go.mod h1:JeRgkft04UBgHMgCIwADu4Pn6Mtm5d4nPKWu0nJ5d+o= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= -github.com/rollkit/celestia-openrpc v0.3.0 h1:jMLsdLNQ7T20yiNDlisBhlyurFOpN1gZ6vC068FPrQA= -github.com/rollkit/celestia-openrpc v0.3.0/go.mod h1:2ZhU01YF2hsHIROWzxfMZOYM09Kgyy4roH5JWoNJzp0= +github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/rollkit/go-da v0.0.0-20231117151938-ee3b613d7a3a h1:d/2491oTlCydpZepyxG66D8s5tT9QG9n4YuemL0eCmQ= github.com/rollkit/go-da v0.0.0-20231117151938-ee3b613d7a3a/go.mod h1:cy1LA9kCyCJHgszKkTh9hJn816l5Oa87GMA2c1imfqA= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= @@ -1438,7 +1403,6 @@ github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6Mwd github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= -github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sivchari/containedctx v1.0.2/go.mod h1:PwZOeqm4/DLoJOqMSIJs3aKqXRX4YO+uXww087KZ7Bw= github.com/sivchari/nosnakecase v1.5.0/go.mod h1:CwDzrzPea40/GB6uynrNLiorAlgFRvRbFSgJx2Gs+QY= github.com/sivchari/tenv v1.6.0/go.mod h1:64yStXKSOxDfX47NlhVwND4dHwfZDdbp2Lyl018Icvg= @@ -1540,9 +1504,6 @@ github.com/tendermint/tm-db v0.6.6/go.mod h1:wP8d49A85B7/erz/r4YbKssKw6ylsO/hKtF github.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0= github.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3/go.mod h1:ON8b8w4BN/kE1EOhwT0o+d62W65a6aPw1nouo9LMgyY= github.com/tetafro/godot v1.4.11/go.mod h1:LR3CJpxDVGlYOWn3ZZg1PgNZdTUvzsZWu8xaEohUpn8= -github.com/tidwall/gjson v1.14.4 h1:uo0p8EbA09J7RQaflQ1aBRffTR7xedD2bcIVSYxLnkM= -github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= -github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/timakin/bodyclose v0.0.0-20210704033933-f49887972144/go.mod h1:Qimiffbc6q9tBWlVV6x0P9sat/ao1xEkREYPPj9hphk= github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg= github.com/tj/assert v0.0.3/go.mod h1:Ne6X72Q+TB1AteidzQncjw9PabbMp4PBMZ1k+vd1Pvk= @@ -1583,11 +1544,8 @@ github.com/whyrusleeping/mdns v0.0.0-20190826153040-b9b60ed33aa9/go.mod h1:j4l84 github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7/go.mod h1:X2c0RVCI1eSUFI8eLcY3c0423ykwiUdxLJtkDvruhjI= github.com/x-cray/logrus-prefixed-formatter v0.5.2/go.mod h1:2duySbKsL6M18s5GU7VPsoEPHyzalCE06qoARUCeBBE= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= -github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs= @@ -1605,10 +1563,6 @@ github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1 github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= -gitlab.com/NebulousLabs/errors v0.0.0-20171229012116-7ead97ef90b8/go.mod h1:ZkMZ0dpQyWwlENaeZVBiQRjhMEZvk6VTXquzl3FOFP8= -gitlab.com/NebulousLabs/errors v0.0.0-20200929122200-06c536cf6975 h1:L/ENs/Ar1bFzUeKx6m3XjlmBgIUlykX9dzvp5k9NGxc= -gitlab.com/NebulousLabs/fastrand v0.0.0-20181126182046-603482d69e40 h1:dizWJqTWjwyD8KGcMOwgrkqu1JIkofYgKkmDeNE7oAs= -gitlab.com/NebulousLabs/fastrand v0.0.0-20181126182046-603482d69e40/go.mod h1:rOnSnoRyxMI3fe/7KIbVcsHRGxe30OONv8dEgo+vCfA= gitlab.com/bosi/decorder v0.2.2/go.mod h1:9K1RB5+VPNQYtXtTDAzd2OEftsZb1oV0IrJrzChSdGE= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= @@ -1704,7 +1658,6 @@ golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190923035154-9ee001bba392/go.mod h1:/lpIB1dKB+9EgE3H3cr1v9wB50oz8l4C4h62xy7jSTY= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20200109152110-61a87790db17/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200221231518-2aa609cf4a9d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200323165209-0ec3e9974c59/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= @@ -2172,8 +2125,6 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20220517211312-f3a8303e98df/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= -golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk= -golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2/go.mod h1:K8+ghG5WaK9qNqU5K3HdILfMLy1f3aNYFI/wnl100a8= gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= gonum.org/v1/gonum v0.11.0 h1:f1IJhK4Km5tBJmaiJXtk/PkL4cdVX6J+tGiM187uT5E= @@ -2463,7 +2414,6 @@ rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sigs.k8s.io/yaml v1.2.0/go.mod h1:yfXDCHCao9+ENCvLSE62v9VSji2MKu5jeNfTrofGhJc= -sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= sourcegraph.com/sourcegraph/go-diff v0.5.0/go.mod h1:kuch7UrkMzY0X+p9CRK03kfuPQ2zzQcaEFbx8wA8rck= sourcegraph.com/sqs/pbtypes v0.0.0-20180604144634-d3ebe8f20ae4/go.mod h1:ketZ/q3QxT9HOBeFhu6RdvsftgpsbFHBF5Cas6cDKZ0= diff --git a/node/full.go b/node/full.go index 7e1dfb14eb..b63e818865 100644 --- a/node/full.go +++ b/node/full.go @@ -11,6 +11,8 @@ import ( ktds "github.com/ipfs/go-datastore/keytransform" "github.com/libp2p/go-libp2p/core/crypto" "go.uber.org/multierr" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" abci "github.com/cometbft/cometbft/abci/types" llcfg "github.com/cometbft/cometbft/config" @@ -21,10 +23,10 @@ import ( rpcclient "github.com/cometbft/cometbft/rpc/client" cmtypes "github.com/cometbft/cometbft/types" + goDAProxy "github.com/rollkit/go-da/proxy" "github.com/rollkit/rollkit/block" "github.com/rollkit/rollkit/config" "github.com/rollkit/rollkit/da" - "github.com/rollkit/rollkit/da/registry" "github.com/rollkit/rollkit/mempool" mempoolv1 "github.com/rollkit/rollkit/mempool/v1" "github.com/rollkit/rollkit/p2p" @@ -63,7 +65,7 @@ type FullNode struct { proxyApp proxy.AppConns eventBus *cmtypes.EventBus - dalc da.DataAvailabilityLayerClient + dalc *da.DAClient p2pClient *p2p.Client hSyncService *block.HeaderSyncService bSyncService *block.BlockSyncService @@ -202,16 +204,13 @@ func initBaseKV(nodeConfig config.NodeConfig, logger log.Logger) (ds.TxnDatastor return store.NewDefaultKVStore(nodeConfig.RootDir, nodeConfig.DBPath, "rollkit") } -func initDALC(nodeConfig config.NodeConfig, dalcKV ds.TxnDatastore, logger log.Logger) (da.DataAvailabilityLayerClient, error) { - dalc := registry.GetClient(nodeConfig.DALayer) - if dalc == nil { - return nil, fmt.Errorf("errror while getting data availability client named '%s'", nodeConfig.DALayer) - } - err := dalc.Init(nodeConfig.NamespaceID, []byte(nodeConfig.DAConfig), dalcKV, logger.With("module", "da_client")) +func initDALC(nodeConfig config.NodeConfig, dalcKV ds.TxnDatastore, logger log.Logger) (*da.DAClient, error) { + daClient := goDAProxy.NewClient() + err := daClient.Start(nodeConfig.DAAddress, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { - return nil, fmt.Errorf("error while initializing data availability layer client: %w", err) + return nil, fmt.Errorf("error while establishing GRPC connection to DA layer: %w", err) } - return dalc, nil + return &da.DAClient{DA: daClient, Logger: logger.With("module", "da_client")}, nil } func initMempool(logger log.Logger, proxyApp proxy.AppConns) *mempoolv1.TxMempool { @@ -236,7 +235,7 @@ func initBlockSyncService(ctx context.Context, mainKV ds.TxnDatastore, nodeConfi return blockSyncService, nil } -func initBlockManager(signingKey crypto.PrivKey, nodeConfig config.NodeConfig, genesis *cmtypes.GenesisDoc, store store.Store, mempool mempool.Mempool, proxyApp proxy.AppConns, dalc da.DataAvailabilityLayerClient, eventBus *cmtypes.EventBus, logger log.Logger, blockSyncService *block.BlockSyncService) (*block.Manager, error) { +func initBlockManager(signingKey crypto.PrivKey, nodeConfig config.NodeConfig, genesis *cmtypes.GenesisDoc, store store.Store, mempool mempool.Mempool, proxyApp proxy.AppConns, dalc *da.DAClient, eventBus *cmtypes.EventBus, logger log.Logger, blockSyncService *block.BlockSyncService) (*block.Manager, error) { blockManager, err := block.NewManager(signingKey, nodeConfig.BlockManagerConfig, genesis, store, mempool, proxyApp.Consensus(), dalc, eventBus, logger.With("module", "BlockManager"), blockSyncService.BlockStore()) if err != nil { return nil, fmt.Errorf("error while initializing BlockManager: %w", err) @@ -331,10 +330,6 @@ func (n *FullNode) OnStart() error { return fmt.Errorf("error while starting block sync service: %w", err) } - if err = n.dalc.Start(); err != nil { - return fmt.Errorf("error while starting data availability layer client: %w", err) - } - if n.nodeConfig.Aggregator { n.Logger.Info("working in aggregator mode", "block time", n.nodeConfig.BlockTime) go n.blockManager.AggregationLoop(n.ctx, n.nodeConfig.LazyAggregator) @@ -367,8 +362,7 @@ func (n *FullNode) GetGenesisChunks() ([]string, error) { func (n *FullNode) OnStop() { n.Logger.Info("halting full node...") n.cancel() - err := n.dalc.Stop() - err = multierr.Append(err, n.p2pClient.Close()) + err := n.p2pClient.Close() err = multierr.Append(err, n.hSyncService.Stop()) err = multierr.Append(err, n.bSyncService.Stop()) err = multierr.Append(err, n.IndexerService.Stop()) diff --git a/node/full_client_test.go b/node/full_client_test.go index 7685c01cf2..f9368864a3 100644 --- a/node/full_client_test.go +++ b/node/full_client_test.go @@ -80,7 +80,7 @@ func getRPC(t *testing.T) (*mocks.Application, *FullClient) { node, err := newFullNode( ctx, config.NodeConfig{ - DALayer: "newda", + DAAddress: MockServerAddr, }, key, signingKey, @@ -188,7 +188,7 @@ func TestGenesisChunked(t *testing.T) { mockApp.On(InitChain, mock.Anything).Return(abci.ResponseInitChain{}) privKey, _, _ := crypto.GenerateEd25519Key(crand.Reader) signingKey, _, _ := crypto.GenerateEd25519Key(crand.Reader) - n, _ := newFullNode(context.Background(), config.NodeConfig{DALayer: "newda"}, privKey, signingKey, proxy.NewLocalClientCreator(mockApp), genDoc, test.NewFileLogger(t)) + n, _ := newFullNode(context.Background(), config.NodeConfig{DAAddress: MockServerAddr}, privKey, signingKey, proxy.NewLocalClientCreator(mockApp), genDoc, test.NewFileLogger(t)) rpc := NewFullClient(n) @@ -497,7 +497,7 @@ func TestTx(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() node, err := newFullNode(ctx, config.NodeConfig{ - DALayer: "newda", + DAAddress: MockServerAddr, Aggregator: true, BlockManagerConfig: config.BlockManagerConfig{ BlockTime: 1 * time.Second, // blocks must be at least 1 sec apart for adjacent headers to get verified correctly @@ -765,8 +765,8 @@ func TestMempool2Nodes(t *testing.T) { defer cancel() // make node1 an aggregator, so that node2 can start gracefully node1, err := newFullNode(ctx, config.NodeConfig{ + DAAddress: MockServerAddr, Aggregator: true, - DALayer: "newda", P2P: config.P2PConfig{ ListenAddress: "/ip4/127.0.0.1/tcp/9001", }, @@ -776,7 +776,7 @@ func TestMempool2Nodes(t *testing.T) { require.NotNil(node1) node2, err := newFullNode(ctx, config.NodeConfig{ - DALayer: "newda", + DAAddress: MockServerAddr, P2P: config.P2PConfig{ ListenAddress: "/ip4/127.0.0.1/tcp/9002", Seeds: "/ip4/127.0.0.1/tcp/9001/p2p/" + id1.Pretty(), @@ -840,7 +840,7 @@ func TestStatus(t *testing.T) { node, err := newFullNode( context.Background(), config.NodeConfig{ - DALayer: "newda", + DAAddress: MockServerAddr, P2P: config.P2PConfig{ ListenAddress: "/ip4/0.0.0.0/tcp/26656", }, @@ -951,7 +951,7 @@ func TestFutureGenesisTime(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() node, err := newFullNode(ctx, config.NodeConfig{ - DALayer: "newda", + DAAddress: MockServerAddr, Aggregator: true, BlockManagerConfig: config.BlockManagerConfig{ BlockTime: 200 * time.Millisecond, diff --git a/node/full_node_integration_test.go b/node/full_node_integration_test.go index e43fc93258..2fe623068b 100644 --- a/node/full_node_integration_test.go +++ b/node/full_node_integration_test.go @@ -23,8 +23,6 @@ import ( "github.com/stretchr/testify/require" "github.com/rollkit/rollkit/config" - mockda "github.com/rollkit/rollkit/da/mock" - "github.com/rollkit/rollkit/store" test "github.com/rollkit/rollkit/test/log" "github.com/rollkit/rollkit/test/mocks" "github.com/rollkit/rollkit/types" @@ -47,12 +45,11 @@ func TestAggregatorMode(t *testing.T) { key, _, _ := crypto.GenerateEd25519Key(rand.Reader) genesisValidators, signingKey := types.GetGenesisValidatorSetWithSigner() blockManagerConfig := config.BlockManagerConfig{ - BlockTime: 1 * time.Second, - NamespaceID: types.NamespaceID{1, 2, 3, 4, 5, 6, 7, 8}, + BlockTime: 1 * time.Second, } ctx, cancel := context.WithCancel(context.Background()) defer cancel() - node, err := newFullNode(ctx, config.NodeConfig{DALayer: "newda", Aggregator: true, BlockManagerConfig: blockManagerConfig}, key, signingKey, proxy.NewLocalClientCreator(app), &cmtypes.GenesisDoc{ChainID: "test", Validators: genesisValidators}, log.TestingLogger()) + node, err := newFullNode(ctx, config.NodeConfig{DAAddress: MockServerAddr, Aggregator: true, BlockManagerConfig: blockManagerConfig}, key, signingKey, proxy.NewLocalClientCreator(app), &cmtypes.GenesisDoc{ChainID: "test", Validators: genesisValidators}, log.TestingLogger()) require.NoError(err) require.NotNil(node) @@ -151,13 +148,12 @@ func TestLazyAggregator(t *testing.T) { // the blocktime too short. in future, we can add a configuration // in go-header syncer initialization to not rely on blocktime, but the // config variable - BlockTime: 1 * time.Second, - NamespaceID: types.NamespaceID{1, 2, 3, 4, 5, 6, 7, 8}, + BlockTime: 1 * time.Second, } ctx, cancel := context.WithCancel(context.Background()) defer cancel() node, err := NewNode(ctx, config.NodeConfig{ - DALayer: "newda", + DAAddress: MockServerAddr, Aggregator: true, BlockManagerConfig: blockManagerConfig, LazyAggregator: true, @@ -468,13 +464,7 @@ func testSingleAggregatorSingleFullNodeSingleLightNode(t *testing.T) { for i := 0; i < num; i++ { keys[i], _, _ = crypto.GenerateEd25519Key(rand.Reader) } - dalc := &mockda.DataAvailabilityLayerClient{} - ds, _ := store.NewDefaultInMemoryKVStore() - _ = dalc.Init([8]byte{}, nil, ds, log.TestingLogger()) - _ = dalc.Start() - defer func() { - require.NoError(dalc.Stop()) - }() + dalc := getMockDA() bmConfig := getBMConfig() sequencer, _ := createNode(aggCtx, 0, true, false, keys, bmConfig, t) fullNode, _ := createNode(ctx, 1, false, false, keys, bmConfig, t) @@ -587,10 +577,7 @@ func createNodes(aggCtx, ctx context.Context, num int, bmConfig config.BlockMana nodes := make([]*FullNode, num) apps := make([]*mocks.Application, num) - dalc := &mockda.DataAvailabilityLayerClient{} - ds, _ := store.NewDefaultInMemoryKVStore() - _ = dalc.Init([8]byte{}, nil, ds, test.NewFileLoggerCustom(t, test.TempLogFileName(t, "dalc"))) - _ = dalc.Start() + dalc := getMockDA() node, app := createNode(aggCtx, 0, true, false, keys, bmConfig, t) apps[0] = app nodes[0] = node.(*FullNode) @@ -646,8 +633,8 @@ func createNode(ctx context.Context, n int, aggregator bool, isLight bool, keys node, err := NewNode( ctx, config.NodeConfig{ + DAAddress: MockServerAddr, P2P: p2pConfig, - DALayer: "newda", Aggregator: aggregator, BlockManagerConfig: bmConfig, Light: isLight, diff --git a/node/helpers.go b/node/helpers.go index 795523c21c..adcee1297a 100644 --- a/node/helpers.go +++ b/node/helpers.go @@ -9,7 +9,6 @@ import ( testutils "github.com/celestiaorg/utils/test" "github.com/rollkit/rollkit/config" - "github.com/rollkit/rollkit/types" ) // Source is an enum representing different sources of height @@ -49,7 +48,6 @@ func getBMConfig() config.BlockManagerConfig { return config.BlockManagerConfig{ DABlockTime: 100 * time.Millisecond, BlockTime: 1 * time.Second, // blocks must be at least 1 sec apart for adjacent headers to get verified correctly - NamespaceID: types.NamespaceID{8, 7, 6, 5, 4, 3, 2, 1}, } } diff --git a/node/helpers_test.go b/node/helpers_test.go index f4972a11de..7c54aacdce 100644 --- a/node/helpers_test.go +++ b/node/helpers_test.go @@ -12,10 +12,14 @@ import ( "github.com/libp2p/go-libp2p/core/crypto" "github.com/stretchr/testify/require" - mockda "github.com/rollkit/rollkit/da/mock" - "github.com/rollkit/rollkit/store" + goDATest "github.com/rollkit/go-da/test" + "github.com/rollkit/rollkit/da" ) +func getMockDA() *da.DAClient { + return &da.DAClient{DA: goDATest.NewDummyDA(), Logger: log.TestingLogger()} +} + func TestMockTester(t *testing.T) { m := MockTester{t} m.Fail() @@ -28,13 +32,7 @@ func TestGetNodeHeight(t *testing.T) { require := require.New(t) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - dalc := &mockda.DataAvailabilityLayerClient{} - ds, _ := store.NewDefaultInMemoryKVStore() - _ = dalc.Init([8]byte{}, nil, ds, log.TestingLogger()) - _ = dalc.Start() - defer func() { - require.NoError(dalc.Stop()) - }() + dalc := getMockDA() num := 2 keys := make([]crypto.PrivKey, num) for i := 0; i < num; i++ { diff --git a/node/node_test.go b/node/node_test.go index 999ff89d77..fc8c006071 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -15,6 +15,8 @@ import ( "github.com/rollkit/rollkit/types" ) +var MockServerAddr = ":7980" + // cleanUpNode stops the node and checks if it is running func cleanUpNode(node Node, t *testing.T) { defer func() { @@ -45,7 +47,7 @@ func initializeAndStartNode(ctx context.Context, t *testing.T, nodeType string) } func newTestNode(ctx context.Context, t *testing.T, nodeType string) (Node, error) { - config := config.NodeConfig{DALayer: "newda"} + config := config.NodeConfig{DAAddress: MockServerAddr} switch nodeType { case "light": config.Light = true diff --git a/rpc/json/helpers_test.go b/rpc/json/helpers_test.go index c2de3c04e4..1663e7e3f1 100644 --- a/rpc/json/helpers_test.go +++ b/rpc/json/helpers_test.go @@ -32,6 +32,8 @@ const ( Commit = "Commit" ) +var MockServerAddr = ":7980" + // copied from rpc func getRPC(t *testing.T) (*mocks.Application, rpcclient.Client) { t.Helper() @@ -63,7 +65,7 @@ func getRPC(t *testing.T) (*mocks.Application, rpcclient.Client) { genesisValidators := []cmtypes.GenesisValidator{ {Address: pubKey.Address(), PubKey: pubKey, Power: int64(100), Name: "gen #1"}, } - n, err := node.NewNode(context.Background(), config.NodeConfig{Aggregator: true, DALayer: "newda", BlockManagerConfig: config.BlockManagerConfig{BlockTime: 1 * time.Second}, Light: false}, key, signingKey, proxy.NewLocalClientCreator(app), &cmtypes.GenesisDoc{ChainID: "test", Validators: genesisValidators}, log.TestingLogger()) + n, err := node.NewNode(context.Background(), config.NodeConfig{DAAddress: MockServerAddr, Aggregator: true, BlockManagerConfig: config.BlockManagerConfig{BlockTime: 1 * time.Second}, Light: false}, key, signingKey, proxy.NewLocalClientCreator(app), &cmtypes.GenesisDoc{ChainID: "test", Validators: genesisValidators}, log.TestingLogger()) require.NoError(err) require.NotNil(n) diff --git a/state/block-executor.md b/state/block-executor.md index 49c9ddbed4..1a41b2a082 100644 --- a/state/block-executor.md +++ b/state/block-executor.md @@ -6,9 +6,9 @@ The `BlockExecutor` is a component responsible for creating, applying, and maint ## Detailed Description -The `BlockExecutor` is initialized with a proposer address, `namespace ID`, `chain ID`, `mempool`, `proxyApp`, `eventBus`, and `logger`. It uses these to manage the creation and application of blocks. It also validates blocks and commits them, updating the state as necessary. +The `BlockExecutor` is initialized with a proposer address, `chain ID`, `mempool`, `proxyApp`, `eventBus`, and `logger`. It uses these to manage the creation and application of blocks. It also validates blocks and commits them, updating the state as necessary. -- `NewBlockExecutor`: This method creates a new instance of `BlockExecutor`. It takes a proposer address, `namespace ID`, `chain ID`, `mempool`, `proxyApp`, `eventBus`, and `logger` as parameters. See [block manager] for details. +- `NewBlockExecutor`: This method creates a new instance of `BlockExecutor`. It takes a proposer address, `chain ID`, `mempool`, `proxyApp`, `eventBus`, and `logger` as parameters. See [block manager] for details. - `InitChain`: This method initializes the chain by calling ABCI `InitChainSync` using the consensus connection to the app. It takes a `GenesisDoc` as a parameter. It sends a ABCI `RequestInitChain` message with the genesis parameters including: - Genesis Time diff --git a/state/executor.go b/state/executor.go index ee91fda7b8..6f06e9d68d 100644 --- a/state/executor.go +++ b/state/executor.go @@ -31,7 +31,6 @@ var ErrAddingValidatorToBased = errors.New("cannot add validators to empty valid // BlockExecutor creates and applies blocks and maintains state. type BlockExecutor struct { proposerAddress []byte - namespaceID types.NamespaceID chainID string proxyApp proxy.AppConnConsensus mempool mempool.Mempool @@ -42,11 +41,9 @@ type BlockExecutor struct { } // NewBlockExecutor creates new instance of BlockExecutor. -// Proposer address and namespace ID will be used in all newly created blocks. -func NewBlockExecutor(proposerAddress []byte, namespaceID [8]byte, chainID string, mempool mempool.Mempool, proxyApp proxy.AppConnConsensus, eventBus *cmtypes.EventBus, logger log.Logger) *BlockExecutor { +func NewBlockExecutor(proposerAddress []byte, chainID string, mempool mempool.Mempool, proxyApp proxy.AppConnConsensus, eventBus *cmtypes.EventBus, logger log.Logger) *BlockExecutor { return &BlockExecutor{ proposerAddress: proposerAddress, - namespaceID: namespaceID, chainID: chainID, proxyApp: proxyApp, mempool: mempool, diff --git a/state/executor_test.go b/state/executor_test.go index 9703965979..7eeb720875 100644 --- a/state/executor_test.go +++ b/state/executor_test.go @@ -49,11 +49,10 @@ func doTestCreateBlock(t *testing.T) { require.NoError(err) require.NotNil(client) - nsID := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} fmt.Println("Made NID") mpool := mempoolv1.NewTxMempool(logger, cfg.DefaultMempoolConfig(), proxy.NewAppConnMempool(client, proxy.NopMetrics()), 0) fmt.Println("Made a NewTxMempool") - executor := NewBlockExecutor([]byte("test address"), nsID, "test", mpool, proxy.NewAppConnConsensus(client, proxy.NopMetrics()), nil, logger) + executor := NewBlockExecutor([]byte("test address"), "test", mpool, proxy.NewAppConnConsensus(client, proxy.NopMetrics()), nil, logger) fmt.Println("Made a New Block Executor") state := types.State{} @@ -112,13 +111,12 @@ func doTestApplyBlock(t *testing.T) { require.NoError(err) require.NotNil(client) - nsID := [8]byte{1, 2, 3, 4, 5, 6, 7, 8} chainID := "test" mpool := mempoolv1.NewTxMempool(logger, cfg.DefaultMempoolConfig(), proxy.NewAppConnMempool(client, proxy.NopMetrics()), 0) eventBus := cmtypes.NewEventBus() require.NoError(eventBus.Start()) - executor := NewBlockExecutor([]byte("test address"), nsID, chainID, mpool, proxy.NewAppConnConsensus(client, proxy.NopMetrics()), eventBus, logger) + executor := NewBlockExecutor([]byte("test address"), chainID, mpool, proxy.NewAppConnConsensus(client, proxy.NopMetrics()), eventBus, logger) txQuery, err := query.New("tm.event='Tx'") require.NoError(err) diff --git a/test/docker/mockserv.Dockerfile b/test/docker/mockserv.Dockerfile index 73b79ef636..fdbcd14327 100644 --- a/test/docker/mockserv.Dockerfile +++ b/test/docker/mockserv.Dockerfile @@ -6,7 +6,7 @@ WORKDIR /src COPY . . RUN go mod tidy -compat=1.19 && \ - go build /src/da/grpc/mockserv/cmd/main.go + go build /src/da/mock/main.go # Final image FROM alpine:3.18.3 diff --git a/types/block.go b/types/block.go index 349e0c5b8c..9d57a330c1 100644 --- a/types/block.go +++ b/types/block.go @@ -11,9 +11,6 @@ import ( cmtypes "github.com/cometbft/cometbft/types" ) -// NamespaceID is a unique identifier of a namespace. -type NamespaceID [8]byte - // Version captures the consensus rules for processing a block in the blockchain, // including all blockchain data structures and the rules of the application's // state transition machine.