This repository has been archived by the owner on Jun 25, 2024. It is now read-only.
forked from lightninglabs/pool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch.go
287 lines (253 loc) · 8 KB
/
batch.go
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
package clientdb
import (
"fmt"
"github.com/getvoltage/pool/account"
"github.com/getvoltage/pool/order"
"go.etcd.io/bbolt"
)
var (
// batchBucketKey is the top level bucket where we can find all
// information about batches we've participated in.
batchBucketKey = []byte("batch")
// pendingBatchIDKey is a key we'll use to store the ID of a batch we're
// currently participating in.
pendingBatchIDKey = []byte("pending-id")
// pendingBatchAccountsBucketKey is the key of a bucket nested within
// the top level batch bucket that is responsible for storing the
// updates of an account that has participated in a batch.
pendingBatchAccountsBucketKey = []byte("pending-accounts")
// pendingBatchOrdersBucketKey is the key of a bucket nested within
// the top level batch bucket that is responsible for storing the
// updates of an order that has matched in a batch.
pendingBatchOrdersBucketKey = []byte("pending-orders")
zeroBatchID order.BatchID
)
// StorePendingBatch atomically stages all modified orders/accounts as a result
// of a pending batch. If any single operation fails, the whole set of changes
// is rolled back. Once the batch has been finalized/confirmed on-chain, then
// the stage modifications will be applied atomically as a result of
// MarkBatchComplete.
func (db *DB) StorePendingBatch(batch *order.Batch, orders []order.Nonce,
orderModifiers [][]order.Modifier, accounts []*account.Account,
accountModifiers [][]account.Modifier) error {
// Catch the most obvious problems first.
if len(orders) != len(orderModifiers) {
return fmt.Errorf("order modifier length mismatch")
}
if len(accounts) != len(accountModifiers) {
return fmt.Errorf("account modifier length mismatch")
}
// Wrap the whole batch update in a single update transaction.
return db.Update(func(tx *bbolt.Tx) error {
// Before updating the set of orders and accounts, we'll first
// delete the buckets containing any existing staged updates.
// This is to done to handle the case where the first version of
// a batch updated an order/account, but its second version
// didn't. Without this, our state would become desynchronized
// with the auction.
bucket, err := getBucket(tx, batchBucketKey)
if err != nil {
return err
}
err = bucket.DeleteBucket(pendingBatchAccountsBucketKey)
if err != nil && err != bbolt.ErrBucketNotFound {
return err
}
err = bucket.DeleteBucket(pendingBatchOrdersBucketKey)
if err != nil && err != bbolt.ErrBucketNotFound {
return err
}
// Update orders first.
ordersBucket, err := getBucket(tx, ordersBucketKey)
if err != nil {
return err
}
pendingOrdersBucket, err := getNestedBucket(
bucket, pendingBatchOrdersBucketKey, true,
)
if err != nil {
return err
}
var updatedOrders []order.Order
for idx, nonce := range orders {
o, err := updateOrder(
ordersBucket, pendingOrdersBucket, nonce,
orderModifiers[idx],
)
if err != nil {
return err
}
updatedOrders = append(updatedOrders, o)
}
// Then update the accounts.
accountsBucket, err := getBucket(tx, accountBucketKey)
if err != nil {
return err
}
pendingAccountsBucket, err := getNestedBucket(
bucket, pendingBatchAccountsBucketKey, true,
)
if err != nil {
return err
}
var updatedAccounts []*account.Account
for idx, acct := range accounts {
accountKey := getAccountKey(acct)
a, err := updateAccount(
accountsBucket, pendingAccountsBucket,
accountKey, accountModifiers[idx],
)
if err != nil {
return err
}
updatedAccounts = append(updatedAccounts, a)
}
// Finally, write the ID and transaction of the pending batch.
batchID := batch.ID
if err := bucket.Put(pendingBatchIDKey, batchID[:]); err != nil {
return err
}
// Before we are done, we store a snapshot of the this batch,
// so we retain this history for later.
snapshot, err := NewSnapshot(
batch, updatedOrders, updatedAccounts,
)
if err != nil {
return err
}
return storePendingBatchSnapshot(tx, snapshot)
})
}
// PendingBatchSnapshot retrieves the snapshot of the currently pending batch.
// If there isn't one, account.ErrNoPendingBatch is returned.
func (db *DB) PendingBatchSnapshot() (*LocalBatchSnapshot, error) {
var batchSnapshot *LocalBatchSnapshot
err := db.View(func(tx *bbolt.Tx) error {
var err error
batchSnapshot, err = fetchPendingBatchSnapshot(tx)
return err
})
return batchSnapshot, err
}
// pendingBatchID retrieves the stored pending batch ID within a database
// transaction.
func pendingBatchID(tx *bbolt.Tx) (order.BatchID, error) {
bucket, err := getBucket(tx, batchBucketKey)
if err != nil {
return zeroBatchID, err
}
pendingBatchID := bucket.Get(pendingBatchIDKey)
if pendingBatchID == nil {
return zeroBatchID, account.ErrNoPendingBatch
}
var batchID order.BatchID
copy(batchID[:], pendingBatchID)
return batchID, nil
}
// DeletePendingBatch removes all references to the current pending batch
// without applying its staged updates to accounts and orders. If no pending
// batch exists, this acts as a no-op.
func (db *DB) DeletePendingBatch() error {
return db.Update(func(tx *bbolt.Tx) error {
bucket, err := getBucket(tx, batchBucketKey)
if err != nil {
return err
}
if err := bucket.Delete(pendingBatchIDKey); err != nil {
return err
}
err = bucket.DeleteBucket(pendingBatchAccountsBucketKey)
if err != nil && err != bbolt.ErrBucketNotFound {
return err
}
err = bucket.DeleteBucket(pendingBatchOrdersBucketKey)
if err != nil && err != bbolt.ErrBucketNotFound {
return err
}
// Also delete the pending batch snapshot, as it will be stored
// together with the pending batch.
return deletePendingSnapshot(tx)
})
}
// MarkBatchComplete marks a pending batch as complete, applying any staged
// modifications necessary, and allowing a trader to participate in a new batch.
// If a pending batch is not found, account.ErrNoPendingBatch is returned.
func (db *DB) MarkBatchComplete() error {
return db.Update(func(tx *bbolt.Tx) error {
pendingID, err := pendingBatchID(tx)
if err != nil {
return err
}
if err := applyBatchUpdates(tx); err != nil {
return err
}
return finalizeBatchSnapshot(tx, pendingID)
})
}
// applyBatchUpdates applies the staged updates for any accounts and orders that
// participated in the latest pending batch.
func applyBatchUpdates(tx *bbolt.Tx) error {
bucket, err := getBucket(tx, batchBucketKey)
if err != nil {
return err
}
// We'll start by first applying the account updates. This simply
// involves fetching the updated state as part of the batch, and copying
// it over to the main account state.
pendingAccounts, err := getNestedBucket(
bucket, pendingBatchAccountsBucketKey, false,
)
if err != nil {
return err
}
accounts, err := getBucket(tx, accountBucketKey)
if err != nil {
return err
}
err = pendingAccounts.ForEach(func(k, v []byte) error {
// Filter out any keys that are not for accounts.
if len(k) != 33 {
return nil
}
_, err := updateAccount(pendingAccounts, accounts, k, nil)
return err
})
if err != nil {
return err
}
// Once we've updated all of the accounts, we can remove the pending
// updates as they've been committed.
if err := bucket.DeleteBucket(pendingBatchAccountsBucketKey); err != nil {
return err
}
// We'll do the same for orders as well.
pendingOrders, err := getNestedBucket(
bucket, pendingBatchOrdersBucketKey, false,
)
if err != nil {
return err
}
orders, err := getBucket(tx, ordersBucketKey)
if err != nil {
return err
}
err = pendingOrders.ForEach(func(k, v []byte) error {
// Filter out any keys that are not nonces.
var nonce order.Nonce
if len(k) != len(nonce) {
return nil
}
copy(nonce[:], k)
return copyOrder(pendingOrders, orders, nonce)
})
if err != nil {
return err
}
// Once again, remove the pending order updates as they've been
// committed.
if err := bucket.DeleteBucket(pendingBatchOrdersBucketKey); err != nil {
return err
}
// Finally, remove the reference to the pending batch ID.
return bucket.Delete(pendingBatchIDKey)
}