-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilestore.go
More file actions
396 lines (346 loc) · 10.7 KB
/
filestore.go
File metadata and controls
396 lines (346 loc) · 10.7 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
package paywall
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/opd-ai/paywall/wallet"
)
// FileStore implements the Store interface for filesystem-based payment tracking.
// It stores each payment as a separate JSON file in a designated directory.
// Thread-safety is ensured through a read-write mutex.
//
// Fields:
// - baseDir: Directory path where payment files are stored
// - mu: Mutex for thread-safe file operations
//
// Related: Store interface
type FileStore struct {
baseDir string
mu sync.RWMutex
}
// NewFileStore creates a new filesystem-based payment store instance.
// It initializes a "./payments" directory if it doesn't exist.
//
// Returns:
// - *FileStore: New payment store configured to use "./payments" directory
//
// Error handling:
// - Creates payments directory with 0755 permissions
// - Silently continues if directory already exists
func NewFileStore(base string) *FileStore {
// Create payments directory if it doesn't exist
baseDir := base
if baseDir == "" {
baseDir = "./payments"
}
os.MkdirAll(baseDir, 0o755)
return &FileStore{baseDir: baseDir}
}
// writePayment is a helper that marshals and writes a payment to disk.
// Must be called with the mutex held.
func (m *FileStore) writePayment(p *Payment) error {
data, err := json.Marshal(p)
if err != nil {
return fmt.Errorf("marshal payment: %w", err)
}
filename := filepath.Join(m.baseDir, p.ID+".json")
return os.WriteFile(filename, data, 0o600)
}
// CreatePayment stores a new payment record as a JSON file.
// The payment ID is used as the filename.
//
// Parameters:
// - p: Payment record to store (must not be nil and must have valid ID)
//
// Returns:
// - error: File creation/write errors or JSON marshaling errors
//
// Thread-safety: Protected by write lock
func (m *FileStore) CreatePayment(p *Payment) error {
m.mu.Lock()
defer m.mu.Unlock()
return m.writePayment(p)
}
// GetPayment retrieves a payment record by ID from its JSON file.
//
// Parameters:
// - id: Payment identifier used as filename (without .json extension)
//
// Returns:
// - *Payment: Payment record if found, nil if not found
// - error: File read errors or JSON unmarshaling errors
//
// Thread-safety: Protected by read lock
func (m *FileStore) GetPayment(id string) (*Payment, error) {
m.mu.RLock()
defer m.mu.RUnlock()
filename := filepath.Join(m.baseDir, id+".json")
data, err := os.ReadFile(filename)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, err
}
var payment Payment
if err := json.Unmarshal(data, &payment); err != nil {
return nil, fmt.Errorf("unmarshal payment: %w", err)
}
// Migrate payment to ensure compatibility with current schema
if err := MigratePayment(&payment); err != nil {
return nil, fmt.Errorf("migrate payment: %w", err)
}
return &payment, nil
}
// UpdatePayment updates an existing payment record file.
// Creates the file if it doesn't exist.
//
// Parameters:
// - p: Payment record with updated fields (must not be nil and must have valid ID)
//
// Returns:
// - error: ErrVersionConflict if concurrent modification detected, file errors otherwise
//
// Thread-safety: Protected by write lock
func (m *FileStore) UpdatePayment(p *Payment) error {
m.mu.Lock()
defer m.mu.Unlock()
// Read existing payment within the write lock to prevent race conditions
filename := filepath.Join(m.baseDir, p.ID+".json")
data, err := os.ReadFile(filename)
// If file exists, check version for optimistic locking
if err == nil {
var existingPayment Payment
if unmarshalErr := json.Unmarshal(data, &existingPayment); unmarshalErr == nil {
// Version mismatch indicates concurrent modification
if existingPayment.Version != p.Version {
return ErrVersionConflict
}
}
// If unmarshal fails, proceed with write (corrupted file case)
}
// If file doesn't exist (os.IsNotExist(err)), proceed with creation
// Increment version before writing
p.Version++
return m.writePayment(p)
}
// ListPendingPayments returns all payment records with less than 1 confirmation.
// Scans all JSON files in the storage directory.
//
// Returns:
// - []*Payment: Slice of pending payments, empty slice if none found
// - error: Directory read errors
//
// Notes:
// - Silently skips non-JSON files
// - Silently skips files with read or parse errors
// - Thread-safety: Protected by read lock
func (m *FileStore) ListPendingPayments() ([]*Payment, error) {
m.mu.RLock()
defer m.mu.RUnlock()
files, err := os.ReadDir(m.baseDir)
if err != nil {
return nil, err
}
var payments []*Payment
for _, file := range files {
if filepath.Ext(file.Name()) != ".json" {
continue
}
data, err := os.ReadFile(filepath.Join(m.baseDir, file.Name()))
if err != nil {
log.Printf("Error reading file %s: %v", file.Name(), err)
continue
}
var payment Payment
if err := json.Unmarshal(data, &payment); err != nil {
log.Printf("Error parsing file %s: %v", file.Name(), err)
continue
}
if payment.Confirmations < 1 {
payments = append(payments, &payment)
}
}
return payments, nil
}
// GetPaymentByAddress retrieves a payment record by Bitcoin address.
// Scans all payment files sequentially until a match is found.
//
// Parameters:
// - addr: Bitcoin address to search for (case-sensitive)
//
// Returns:
// - *Payment: Matching payment record, nil if not found
// - error: Directory read errors
//
// Notes:
// - Silently skips non-JSON files
// - Silently skips files with read or parse errors
// - Thread-safety: Protected by read lock
func (m *FileStore) GetPaymentByAddress(addr string) (*Payment, error) {
m.mu.RLock()
defer m.mu.RUnlock()
files, err := os.ReadDir(m.baseDir)
if err != nil {
return nil, err
}
for _, file := range files {
if filepath.Ext(file.Name()) != ".json" {
continue
}
data, err := os.ReadFile(filepath.Join(m.baseDir, file.Name()))
if err != nil {
continue
}
var payment Payment
if err := json.Unmarshal(data, &payment); err != nil {
continue
}
if addr != "" {
if payment.Addresses[wallet.Bitcoin] == addr {
return &payment, nil
}
if payment.Addresses[wallet.Monero] == addr {
return &payment, nil
}
}
}
return nil, nil
}
// GetPendingMultisigPayments returns all pending payments that have multisig enabled.
// Scans all payment files sequentially and filters by multisig status and pending state.
//
// Returns:
// - []*Payment: Slice of pending multisig payments
// - error: Directory read errors
//
// Notes:
// - Silently skips non-JSON files and parse errors
// - Thread-safety: Protected by read lock
func (m *FileStore) GetPendingMultisigPayments() ([]*Payment, error) {
m.mu.RLock()
defer m.mu.RUnlock()
files, err := os.ReadDir(m.baseDir)
if err != nil {
return nil, err
}
var payments []*Payment
for _, file := range files {
if filepath.Ext(file.Name()) != ".json" {
continue
}
data, err := os.ReadFile(filepath.Join(m.baseDir, file.Name()))
if err != nil {
continue
}
var payment Payment
if err := json.Unmarshal(data, &payment); err != nil {
continue
}
if payment.MultisigEnabled && payment.Status == StatusPending {
payments = append(payments, &payment)
}
}
return payments, nil
}
// GetEscrowsExpiringBefore returns escrow payments expiring before the deadline.
// This currently scans and unmarshals all payment JSON files in the data directory.
//
// Parameters:
// - deadline: Time threshold - returns escrows expiring before this time
//
// Returns:
// - []*Payment: Slice of escrow payments with EscrowTimeout before deadline
// - error: Directory read errors
//
// Notes:
// - Silently skips non-JSON files and parse errors
// - Thread-safety: Protected by read lock
// - For better performance at scale, consider indexing by timeout
func (m *FileStore) GetEscrowsExpiringBefore(deadline time.Time) ([]*Payment, error) {
m.mu.RLock()
defer m.mu.RUnlock()
files, err := os.ReadDir(m.baseDir)
if err != nil {
return nil, err
}
var expiring []*Payment
for _, file := range files {
if filepath.Ext(file.Name()) != ".json" {
continue
}
data, err := os.ReadFile(filepath.Join(m.baseDir, file.Name()))
if err != nil {
continue
}
var payment Payment
if err := json.Unmarshal(data, &payment); err != nil {
continue
}
if !payment.MultisigEnabled {
continue
}
if payment.EscrowState != EscrowFunded && payment.EscrowState != EscrowDisputed {
continue
}
// Check if timeout is before deadline
if !payment.EscrowTimeout.IsZero() && payment.EscrowTimeout.Before(deadline) {
expiring = append(expiring, &payment)
}
}
return expiring, nil
}
// FileStoreConfig defines configuration parameters for file-based payment storage
//
// Fields:
// - DataDir: Directory path where payment files will be stored
// - EncryptionKey: Optional 32-byte key for AES-256 encryption (if nil, no encryption)
//
// Security:
// - DataDir should have appropriate filesystem permissions (0755)
// - EncryptionKey must be securely generated and stored if provided
// - When EncryptionKey is provided, files are stored with AES-256-GCM encryption
type FileStoreConfig struct {
DataDir string
EncryptionKey []byte // Optional: 32-byte key for AES-256 encryption
}
// NewFileStoreWithConfig creates a new filesystem-based payment store with configuration.
// If encryption key is provided, returns an EncryptedFileStore, otherwise returns a standard FileStore.
//
// Parameters:
// - config: FileStoreConfig containing storage location and optional encryption key
//
// Returns:
// - PaymentStore: Either *FileStore or *EncryptedFileStore depending on encryption key
// - error: If directory creation fails or encryption setup fails
//
// Security:
// - Creates directory with 0755 permissions
// - Validates encryption key length (must be 32 bytes if provided)
// - Uses AES-256-GCM encryption when key is provided
//
// Related: FileStore, EncryptedFileStore, PaymentStore interface
func NewFileStoreWithConfig(config FileStoreConfig) (PaymentStore, error) {
// Create directory if it doesn't exist
if config.DataDir == "" {
config.DataDir = "./payments"
}
if err := os.MkdirAll(config.DataDir, 0o755); err != nil {
return nil, fmt.Errorf("create storage directory: %w", err)
}
// If encryption key provided, use encrypted store
if config.EncryptionKey != nil {
if len(config.EncryptionKey) != 32 {
return nil, fmt.Errorf("encryption key must be 32 bytes, got %d", len(config.EncryptionKey))
}
// For encrypted store, we need to save the key to a file
keyPath := filepath.Join(config.DataDir, "store.key")
return NewEncryptedFileStore(keyPath, config.DataDir)
}
// Use standard file store without encryption
return NewFileStore(config.DataDir), nil
}