forked from coinbase/mesh-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
types.go
318 lines (272 loc) · 9.86 KB
/
types.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
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
// Copyright 2024 Coinbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package reconciler
import (
"context"
"sync"
"time"
"github.com/TheArcadiaGroup/rosetta-sdk-go/parser"
"github.com/TheArcadiaGroup/rosetta-sdk-go/storage/database"
"github.com/TheArcadiaGroup/rosetta-sdk-go/utils"
"github.com/coinbase/rosetta-sdk-go/types"
)
const (
// ActiveReconciliation is included in the reconciliation
// error message if reconciliation failed during active
// reconciliation.
ActiveReconciliation = "ACTIVE"
// InactiveReconciliation is included in the reconciliation
// error message if reconciliation failed during inactive
// reconciliation.
InactiveReconciliation = "INACTIVE"
)
const (
// BlockGone is when the block where a reconciliation
// is supposed to happen is orphaned.
BlockGone = "BLOCK_GONE"
// HeadBehind is when the synced tip (where balances
// were last computed) is behind the *types.BlockIdentifier
// returned by the call to /account/balance.
HeadBehind = "HEAD_BEHIND"
// BacklogFull is when the reconciliation backlog is full.
BacklogFull = "BACKLOG_FULL"
// TipFailure is returned when looking up the live
// balance fails but we are at tip. This usually occurs
// when the node processes an re-org that we have yet
// to process (so the index we are querying at may be
// ahead of the nodes tip).
TipFailure = "TIP_FAILURE"
// AccountMissing is returned when looking up computed
// balance fails because the account does not exist in
// balance storage.
// This can happen when interesting accounts
// are specified. We try to reconcile balances for
// each of these accounts at each block height.
// But, until we encounter a block with an interesting account
// in it, there is no entry for it in balance storage.
// So, we can not reconcile.
AccountMissing = "ACCOUNT_MISSING"
)
const (
// pruneActiveReconciliation indicates if historical balances
// should be pruned during active reconciliation.
pruneActiveReconciliation = true
// pruneInactiveReconciliation indicates if historical balances
// should be pruned during inactive reconciliation.
pruneInactiveReconciliation = false
)
const (
// defaultBacklogSize is the limit of account lookups
// that can be enqueued to reconcile before new
// requests are dropped.
defaultBacklogSize = 250000
// waitToCheckDiff is the syncing difference (live-head)
// to retry instead of exiting. In other words, if the
// processed head is behind the live head by <
// waitToCheckDiff we should try again after sleeping.
// TODO: Make configurable
waitToCheckDiff = 10
// waitToCheckDiffSleep is the amount of time to wait
// to check a balance difference if the syncer is within
// waitToCheckDiff from the block a balance was queried at.
waitToCheckDiffSleep = 5 * time.Second
// zeroString is a string of value 0.
zeroString = "0"
// inactiveReconciliationSleep is used as the time.Duration
// to sleep when there are no seen accounts to reconcile.
inactiveReconciliationSleep = 1 * time.Second
// defaultInactiveFrequency is the minimum
// number of blocks the reconciler should wait between
// inactive reconciliations for each account.
defaultInactiveFrequency = 200
// defaultReconcilerConcurrency is the number of goroutines
// to start for reconciliation. Half of the goroutines are assigned
// to inactive reconciliation and half are assigned to active
// reconciliation.
defaultReconcilerConcurrency = 8
// safeBalancePruneDepth is the depth from the last balance
// change that we consider safe to prune. We are very conservative
// here to prevent removing balances we may need in a reorg.
safeBalancePruneDepth = int64(500) // nolint:gomnd
// shardBuffer is multiplied by inactive concurrency +
// active concurrency to determine how many shards should
// be created in the queueMap. The more shards created,
// the less lock contention we will encounter.
shardBuffer = 2
// processQueueBacklog is the maximum number of blocks
// we can get behind the syncing loop without blocking.
processQueueBacklog = 1000
)
// Helper functions are used by Reconciler to compare
// computed balances from a block with the balance calculated
// by the node. Defining an interface allows the client to determine
// what sort of storage layer they want to use to provide the required
// information.
type Helper interface {
DatabaseTransaction(ctx context.Context) database.Transaction
CurrentBlock(
ctx context.Context,
dbTx database.Transaction,
) (*types.BlockIdentifier, error)
IndexAtTip(
ctx context.Context,
index int64,
) (bool, error)
CanonicalBlock(
ctx context.Context,
dbTx database.Transaction,
block *types.BlockIdentifier,
) (bool, error)
ComputedBalance(
ctx context.Context,
dbTx database.Transaction,
account *types.AccountIdentifier,
currency *types.Currency,
index int64,
) (*types.Amount, error)
LiveBalance(
ctx context.Context,
account *types.AccountIdentifier,
currency *types.Currency,
index int64,
) (*types.Amount, *types.BlockIdentifier, error)
// PruneBalances is invoked by the reconciler
// to indicate that all historical balance states
// <= to index can be removed.
PruneBalances(
ctx context.Context,
account *types.AccountIdentifier,
currency *types.Currency,
index int64,
) error
// ForceInactiveReconciliation is invoked by the
// inactive reconciler when the next account to
// reconcile has been checked within the configured
// inactive reconciliation frequency. This allows
// the helper to dynamically force inactive reconciliation
// when desired (i.e. when at tip).
ForceInactiveReconciliation(
ctx context.Context,
account *types.AccountIdentifier,
currency *types.Currency,
lastCheck *types.BlockIdentifier,
) bool
}
// Handler is called by Reconciler after a reconciliation
// is performed. When a reconciliation failure is observed,
// it is up to the client to trigger a halt (by returning
// an error) or to continue (by returning nil).
type Handler interface {
ReconciliationFailed(
ctx context.Context,
reconciliationType string,
account *types.AccountIdentifier,
currency *types.Currency,
computedBalance string,
liveBalance string,
block *types.BlockIdentifier,
) error
ReconciliationSucceeded(
ctx context.Context,
reconciliationType string,
account *types.AccountIdentifier,
currency *types.Currency,
balance string,
block *types.BlockIdentifier,
) error
ReconciliationExempt(
ctx context.Context,
reconciliationType string,
account *types.AccountIdentifier,
currency *types.Currency,
computedBalance string,
liveBalance string,
block *types.BlockIdentifier,
exemption *types.BalanceExemption,
) error
ReconciliationSkipped(
ctx context.Context,
reconciliationType string,
account *types.AccountIdentifier,
currency *types.Currency,
cause string,
) error
}
// InactiveEntry is used to track the last
// time that an *types.AccountCurrency was reconciled.
type InactiveEntry struct {
Entry *types.AccountCurrency
LastCheck *types.BlockIdentifier
}
// blockRequest is used to enqueue processed
// blocks for reconciliation.
type blockRequest struct {
Block *types.BlockIdentifier
Changes []*parser.BalanceChange
}
// Reconciler contains all logic to reconcile balances of
// types.AccountIdentifiers returned in types.Operations
// by a Rosetta Server.
type Reconciler struct {
helper Helper
handler Handler
parser *parser.Parser
lookupBalanceByBlock bool
interestingAccounts []*types.AccountCurrency
backlogSize int
changeQueue chan *parser.BalanceChange
inactiveFrequency int64
debugLogging bool
balancePruning bool
// Reconciler concurrency is separated between
// active and inactive concurrency to allow for
// fine-grained tuning of reconciler behavior.
// When there are many transactions in a block
// on a resource-constrained machine (laptop),
// it is useful to allocate more resources to
// active reconciliation as it is synchronous
// (when lookupBalanceByBlock is enabled).
ActiveConcurrency int
InactiveConcurrency int
// highWaterMark is used to skip requests when
// we are very far behind the live head.
highWaterMark int64
// seenAccounts are stored for inactive account
// reconciliation. seenAccounts must be stored
// separately from inactiveQueue to prevent duplicate
// accounts from being added to the inactive reconciliation
// queue. If this is not done, it is possible a goroutine
// could be processing an account (not in the queue) when
// we do a lookup to determine if we should add to the queue.
seenAccounts map[string]struct{}
inactiveQueue []*InactiveEntry
// inactiveQueueMutex needed because we can't peek at the tip
// of a channel to determine when it is ready to look at.
inactiveQueueMutex *utils.PriorityMutex
// lastIndexChecked is the last block index reconciled actively.
lastIndexMutex sync.Mutex
lastIndexChecked int64
// queueMap tracks the *types.AccountCurrency items
// in the active reconciliation queue and being actively
// reconciled. It ensures we don't accidentally attempt to prune
// computed balances being used by other goroutines.
queueMap *utils.ShardedMap
// processQueue is a buffered channel of recently processed
// blocks that must be parsed for reconciliation. We enqueue
// blocks asynchronously so that we don't slow down the sync
// loop.
processQueue chan *blockRequest
// store customized data
metaData string
}