-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcelestia_server_test.go
More file actions
401 lines (333 loc) · 11.3 KB
/
celestia_server_test.go
File metadata and controls
401 lines (333 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package celestia
import (
"bytes"
"context"
"encoding/hex"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/celestiaorg/op-alt-da/metrics"
altda "github.com/ethereum-optimism/optimism/op-alt-da"
"github.com/ethereum/go-ethereum/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// mockStore is a mock implementation of the Store interface for testing.
// It allows testing server handlers without actual Celestia network calls.
type mockStore struct {
getFunc func(ctx context.Context, key []byte) ([]byte, error)
putFunc func(ctx context.Context, data []byte) ([]byte, []byte, error)
}
func (m *mockStore) Get(ctx context.Context, key []byte) ([]byte, error) {
if m.getFunc != nil {
return m.getFunc(ctx, key)
}
return nil, errors.New("mock: Get not implemented")
}
func (m *mockStore) Put(ctx context.Context, data []byte) ([]byte, []byte, error) {
if m.putFunc != nil {
return m.putFunc(ctx, data)
}
return nil, nil, errors.New("mock: Put not implemented")
}
// createTestServer creates a CelestiaServer for testing with mocked storage.
func createTestServer(t *testing.T, store Store) *CelestiaServer {
logger := log.New()
return NewCelestiaServer(
"127.0.0.1",
0, // port 0 = let OS assign
store,
30*time.Second, // submitTimeout
30*time.Second, // getTimeout
30*time.Second, // httpReadTimeout
120*time.Second, // httpWriteTimeout
60*time.Second, // httpIdleTimeout
2*1024*1024, // maxBlobSize (2MB)
false, // metrics disabled for unit tests
0,
nil, // fallback provider (nil = NoopProvider)
logger,
)
}
// validCommitment creates a valid commitment for testing.
// Format: 0x01 (generic) + 0x0c (celestia version) + BlobID
func validCommitment() string {
// Create a valid compact BlobID (40 bytes):
// 8 bytes height + 32 bytes commitment
blobID := make([]byte, 40)
blobID[0] = 0x01 // height byte 1
for i := 8; i < 40; i++ {
blobID[i] = byte(i) // fake commitment
}
// Full commitment: 0x01 (generic) + 0x0c (version) + blobID
comm := append([]byte{0x01, VersionByte}, blobID...)
return "0x" + hex.EncodeToString(comm)
}
// TestHandleHealth verifies the health endpoint returns 200 OK.
func TestHandleHealth(t *testing.T) {
server := &CelestiaServer{
log: log.New(),
}
req := httptest.NewRequest(http.MethodGet, "/health", nil)
w := httptest.NewRecorder()
server.HandleHealth(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "OK", w.Body.String())
}
// TestHandlePut_EmptyBlob verifies that empty blob data returns 400 Bad Request.
func TestHandlePut_EmptyBlob(t *testing.T) {
server := &CelestiaServer{
log: log.New(),
submitTimeout: 30 * time.Second,
maxBlobSize: 2 * 1024 * 1024, // 2MB
}
// Test empty body
req := httptest.NewRequest(http.MethodPut, "/put", bytes.NewReader([]byte{}))
w := httptest.NewRecorder()
server.HandlePut(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Contains(t, w.Body.String(), "empty blob not allowed")
}
// TestHandlePut_WrongRoute verifies that wrong PUT routes return 400.
func TestHandlePut_WrongRoute(t *testing.T) {
server := &CelestiaServer{
log: log.New(),
maxBlobSize: 2 * 1024 * 1024, // 2MB
}
req := httptest.NewRequest(http.MethodPut, "/put/extra/path", bytes.NewReader([]byte("data")))
w := httptest.NewRecorder()
server.HandlePut(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
}
// TestHandleGet_InvalidCommitmentFormat verifies invalid hex returns 400.
func TestHandleGet_InvalidCommitmentFormat(t *testing.T) {
server := &CelestiaServer{
log: log.New(),
getTimeout: 30 * time.Second,
}
// Test invalid hex commitment
req := httptest.NewRequest(http.MethodGet, "/get/0xZZZZ", nil)
w := httptest.NewRecorder()
server.HandleGet(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
}
// TestHandleGet_WrongRoute verifies wrong route returns 400.
func TestHandleGet_WrongRoute(t *testing.T) {
server := &CelestiaServer{
log: log.New(),
}
req := httptest.NewRequest(http.MethodGet, "/wrong/path", nil)
w := httptest.NewRecorder()
server.HandleGet(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code)
}
// TestHandleGet_TooShortCommitment verifies short commitments return error.
func TestHandleGet_TooShortCommitment(t *testing.T) {
store := &mockStore{
getFunc: func(ctx context.Context, key []byte) ([]byte, error) {
return nil, errors.New("should not be called for short commitment")
},
}
server := createTestServer(t, store)
// Test commitment that's too short (less than 40 bytes = minimum BlobID)
req := httptest.NewRequest(http.MethodGet, "/get/0x0102030405", nil)
w := httptest.NewRecorder()
server.HandleGet(w, req)
// Should return 500 because commitment can't be parsed (actual error, not "not found")
assert.True(t, w.Code == http.StatusBadRequest || w.Code == http.StatusInternalServerError,
"Expected 400 or 500 for invalid short commitment, got %d", w.Code)
}
// TestHandleGet_Success verifies successful blob retrieval returns 200.
func TestHandleGet_Success(t *testing.T) {
expectedData := []byte("hello world blob data")
store := &mockStore{
getFunc: func(ctx context.Context, key []byte) ([]byte, error) {
return expectedData, nil
},
}
server := createTestServer(t, store)
req := httptest.NewRequest(http.MethodGet, "/get/"+validCommitment(), nil)
w := httptest.NewRecorder()
server.HandleGet(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, expectedData, w.Body.Bytes())
assert.Equal(t, "application/octet-stream", w.Header().Get("Content-Type"))
}
// TestHandleGet_NotFound verifies missing blob returns 404.
func TestHandleGet_NotFound(t *testing.T) {
store := &mockStore{
getFunc: func(ctx context.Context, key []byte) ([]byte, error) {
return nil, altda.ErrNotFound
},
}
server := createTestServer(t, store)
req := httptest.NewRequest(http.MethodGet, "/get/"+validCommitment(), nil)
w := httptest.NewRecorder()
server.HandleGet(w, req)
assert.Equal(t, http.StatusNotFound, w.Code)
}
// TestHandleGet_InternalError verifies server errors return 500.
func TestHandleGet_InternalError(t *testing.T) {
store := &mockStore{
getFunc: func(ctx context.Context, key []byte) ([]byte, error) {
return nil, errors.New("connection to celestia failed")
},
}
server := createTestServer(t, store)
req := httptest.NewRequest(http.MethodGet, "/get/"+validCommitment(), nil)
w := httptest.NewRecorder()
server.HandleGet(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
}
// TestHandlePut_Success verifies successful blob submission returns 200.
func TestHandlePut_Success(t *testing.T) {
expectedCommitment := []byte{0x01, 0x0c, 0xde, 0xad, 0xbe, 0xef}
store := &mockStore{
putFunc: func(ctx context.Context, data []byte) ([]byte, []byte, error) {
return expectedCommitment, data, nil
},
}
server := createTestServer(t, store)
blobData := []byte("test blob data to submit")
req := httptest.NewRequest(http.MethodPut, "/put", bytes.NewReader(blobData))
w := httptest.NewRecorder()
server.HandlePut(w, req)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, expectedCommitment, w.Body.Bytes())
}
// TestHandlePut_InternalError verifies submission errors return 500.
func TestHandlePut_InternalError(t *testing.T) {
store := &mockStore{
putFunc: func(ctx context.Context, data []byte) ([]byte, []byte, error) {
return nil, nil, errors.New("celestia submission failed")
},
}
server := createTestServer(t, store)
blobData := []byte("test blob data")
req := httptest.NewRequest(http.MethodPut, "/put", bytes.NewReader(blobData))
w := httptest.NewRecorder()
server.HandlePut(w, req)
assert.Equal(t, http.StatusInternalServerError, w.Code)
}
// TestMetricsRecording verifies metrics are recorded correctly.
func TestMetricsRecording(t *testing.T) {
registry := prometheus.NewRegistry()
m := metrics.NewCelestiaMetrics(registry)
// Record various operations
m.RecordHTTPRequest("get", 100*time.Millisecond)
m.RecordHTTPRequest("put", 5*time.Second)
m.RecordSubmission(10*time.Second, 4096)
m.RecordRetrieval(500*time.Millisecond, 2048)
m.SetInclusionHeight(12345)
m.RecordSubmissionError()
m.RecordRetrievalError()
// Verify metrics were recorded
metricFamilies, err := registry.Gather()
require.NoError(t, err)
expectedMetrics := []string{
"op_altda_request_duration_seconds",
"op_altda_blob_size_bytes",
"op_altda_inclusion_height",
"celestia_submission_duration_seconds",
"celestia_submissions_total",
"celestia_submission_errors_total",
"celestia_retrieval_duration_seconds",
"celestia_retrievals_total",
"celestia_retrieval_errors_total",
}
foundMetrics := make(map[string]bool)
for _, mf := range metricFamilies {
foundMetrics[mf.GetName()] = true
}
for _, expected := range expectedMetrics {
assert.True(t, foundMetrics[expected], "Expected metric %s to be registered", expected)
}
}
// TestServerEndpoints verifies that all expected endpoints are registered.
func TestServerEndpoints(t *testing.T) {
server := &CelestiaServer{
log: log.New(),
endpoint: "127.0.0.1:0",
submitTimeout: 30 * time.Second,
getTimeout: 30 * time.Second,
maxBlobSize: 2 * 1024 * 1024, // 2MB
httpServer: &http.Server{},
}
// Test that endpoints are handled correctly
endpoints := []struct {
method string
path string
want int // expected status code for basic request
}{
{http.MethodGet, "/health", http.StatusOK},
{http.MethodPut, "/put", http.StatusBadRequest}, // empty body = 400
{http.MethodGet, "/get/invalid", http.StatusBadRequest},
}
for _, ep := range endpoints {
t.Run(ep.method+"_"+strings.TrimPrefix(ep.path, "/"), func(t *testing.T) {
var req *http.Request
if ep.method == http.MethodPut {
req = httptest.NewRequest(ep.method, ep.path, bytes.NewReader([]byte{}))
} else {
req = httptest.NewRequest(ep.method, ep.path, nil)
}
w := httptest.NewRecorder()
switch {
case strings.HasPrefix(ep.path, "/health"):
server.HandleHealth(w, req)
case strings.HasPrefix(ep.path, "/put"):
server.HandlePut(w, req)
case strings.HasPrefix(ep.path, "/get"):
server.HandleGet(w, req)
}
assert.Equal(t, ep.want, w.Code, "endpoint %s %s", ep.method, ep.path)
})
}
}
// TestBlobIDVersioning ensures proper handling of different commitment formats.
func TestBlobIDVersioning(t *testing.T) {
// Test CelestiaBlobID encoding/decoding at different formats
testCases := []struct {
name string
blobID CelestiaBlobID
expectLen int
}{
{
name: "compact format",
blobID: CelestiaBlobID{
Height: 12345,
Commitment: make([]byte, CommitmentSize),
},
expectLen: CompactBlobIDSize,
},
{
name: "full format",
blobID: CelestiaBlobID{
Height: 12345,
Commitment: make([]byte, CommitmentSize),
ShareOffset: 10,
ShareSize: 100,
},
expectLen: FullBlobIDSize,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Set isCompact based on expected length
if tc.expectLen == CompactBlobIDSize {
tc.blobID.SetCompact(true)
}
data, err := tc.blobID.MarshalBinary()
require.NoError(t, err)
assert.Len(t, data, tc.expectLen)
var decoded CelestiaBlobID
err = decoded.UnmarshalBinary(data)
require.NoError(t, err)
assert.Equal(t, tc.blobID.Height, decoded.Height)
})
}
}