Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | 57x 57x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 5x 26x 26x 26x 26x 26x 26x 26x 26x 98x 98x 318x 318x 140x 140x 140x 50x 50x 50x 14x 14x 14x 14x 20x 20x 20x 20x 20x 140x 140x 140x 138x 140x 50x 50x 50x 49x 50x 33x 33x 33x 33x 33x 14x 20x 20x 20x 20x 20x 26x 17x 17x 17x 67x 67x 53x 22x 53x 53x 53x 59x 59x 62x 3x 3x 3x 3x 7x 7x 7x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 1x 1x 1x 11x 11x 11x 11x 9x 9x 9x 20x 20x 20x 20x 1x 1x 1x 9x 9x 11x 11x 11x 11x 14x 14x 14x 14x 14x 14x 14x 14x 47x 47x 47x 47x 47x 47x 47x 47x 14x 14x 16x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x | import { AbortActionArgs, AbortActionResult, InternalizeActionArgs, InternalizeActionResult, ListActionsArgs, ListActionsResult, ListCertificatesResult, ListOutputsArgs, ListOutputsResult, RelinquishCertificateArgs, RelinquishOutputArgs } from '@bsv/sdk'
import { entity, sdk, StorageProvider, StorageSyncReader, table, wait } from "../index.client";
/**
* The `SignerStorage` class delivers authentication checking storage access to the wallet.
*
* If manages multiple `StorageBase` derived storage services: one actice, the rest as backups.
*
* Of the storage services, one is 'active' at any one time.
* On startup, and whenever triggered by the wallet, `SignerStorage` runs a syncrhonization sequence:
*
* 1. While synchronizing, all other access to storage is blocked waiting.
* 2. The active service is confirmed, potentially triggering a resolution process if there is disagreement.
* 3. Changes are pushed from the active storage service to each inactive, backup service.
*
* Some storage services do not support multiple writers. `SignerStorage` manages wait-blocking write requests
* for these services.
*/
export class WalletStorageManager implements sdk.WalletStorage {
stores: sdk.WalletStorageProvider[] = []
_authId: sdk.AuthId
_services?: sdk.WalletServices
_userIdentityKeyToId: Record<string, number> = {}
_readerCount: number = 0
_writerCount: number = 0
/**
* if true, allow only a single writer to proceed at a time.
* queue the blocked requests so they get executed in order when released.
*/
_isSingleWriter: boolean = true
/**
* if true, allow no new reader or writers to proceed.
* queue the blocked requests so they get executed in order when released.
*/
_syncLocked: boolean = false
/**
* if true, allow no new reader or writers or sync to proceed.
* queue the blocked requests so they get executed in order when released.
*/
_storageProviderLocked: boolean = false
constructor(identityKey: string, active?: sdk.WalletStorageProvider, backups?: sdk.WalletStorageProvider[]) {
this.stores = []
if (active) this.stores.push(active)
if (backups) this.stores = this.stores.concat(backups);
this._authId = { identityKey }
}
isStorageProvider(): boolean { return false }
async getUserId(): Promise<number> {
let userId = this._authId.userId
if (!userId) {
Iif (!this.isAvailable()) await this.makeAvailable()
const { user, isNew } = await this.getActive().findOrInsertUser(this._authId.identityKey)
Iif (!user)
throw new sdk.WERR_INVALID_PARAMETER('identityKey', 'exist on storage.');
userId = user.userId
this._authId.userId = userId
}
return userId
}
async getAuth(): Promise<sdk.AuthId> {
if (!this._authId.userId) this._authId.userId = await this.getUserId();
return this._authId
}
getActive(): sdk.WalletStorageProvider {
Iif (this.stores.length < 1)
throw new sdk.WERR_INVALID_OPERATION('An active WalletStorageProvider must be added to this WalletStorageManager')
return this.stores[0]
}
async getActiveForWriter(): Promise<sdk.WalletStorageWriter> {
while (this._storageProviderLocked || this._syncLocked || this._isSingleWriter && this._writerCount > 0) {
await wait(100)
}
this._writerCount++
return this.getActive()
}
async getActiveForReader(): Promise<sdk.WalletStorageReader> {
while (this._storageProviderLocked || this._syncLocked || this._isSingleWriter && this._writerCount > 0) {
await wait(100)
}
this._readerCount++
return this.getActive()
}
async getActiveForSync(): Promise<sdk.WalletStorageSync> {
// Wait for a current sync task to complete...
while (this._syncLocked) { await wait(100) }
// Set syncLocked which prevents any new storageProvider, readers or writers...
this._syncLocked = true
// Wait for any current storageProvider, readers and writers to complete
while (this._storageProviderLocked || this._readerCount > 0 || this._writerCount > 0) { await wait(100) }
// Allow the sync to proceed on the active store.
return this.getActive()
}
async getActiveForStorageProvider(): Promise<StorageProvider> {
// Wait for a current storageProvider call to complete...
while (this._storageProviderLocked) { await wait(100) }
// Set storageProviderLocked which prevents any new sync, readers or writers...
this._storageProviderLocked = true
// Wait for any current sync, readers and writers to complete
while (this._syncLocked || this._readerCount > 0 || this._writerCount > 0) { await wait(100) }
// We can finally confirm that active storage is still able to support `StorageProvider`
Iif (!this.getActive().isStorageProvider())
throw new sdk.WERR_INVALID_OPERATION('Active "WalletStorageProvider" does not support "StorageProvider" interface.');
// Allow the sync to proceed on the active store.
return this.getActive() as unknown as StorageProvider
}
async runAsWriter<R>(writer: (active: sdk.WalletStorageWriter) => Promise<R>): Promise<R> {
try {
const active = await this.getActiveForWriter()
const r = await writer(active)
return r
} finally {
this._writerCount--
}
}
async runAsReader<R>(reader: (active: sdk.WalletStorageReader) => Promise<R>): Promise<R> {
try {
const active = await this.getActiveForReader()
const r = await reader(active)
return r
} finally {
this._readerCount--
}
}
/**
*
* @param sync the function to run with sync access lock
* @param activeSync from chained sync functions, active storage already held under sync access lock.
* @returns
*/
async runAsSync<R>(sync: (active: sdk.WalletStorageSync) => Promise<R>, activeSync?: sdk.WalletStorageSync): Promise<R> {
try {
const active = activeSync || await this.getActiveForSync()
const r = await sync(active)
return r
} finally {
if (!activeSync)
this._syncLocked = false;
}
}
async runAsStorageProvider<R>(sync: (active: StorageProvider) => Promise<R>): Promise<R> {
try {
const active = await this.getActiveForStorageProvider()
const r = await sync(active)
return r
} finally {
this._storageProviderLocked = false
}
}
/**
*
* @returns true if the active `WalletStorageProvider` also implements `StorageProvider`
*/
isActiveStorageProvider(): boolean {
return this.getActive().isStorageProvider()
}
isAvailable(): boolean {
return this.getActive().isAvailable()
}
async addWalletStorageProvider(provider: sdk.WalletStorageProvider) : Promise<void> {
await provider.makeAvailable()
if (this._services) provider.setServices(this._services)
this.stores.push(provider)
}
setServices(v: sdk.WalletServices) {
this._services = v
for (const store of this.stores)
store.setServices(v)
}
getServices(): sdk.WalletServices {
Iif (!this._services)
throw new sdk.WERR_INVALID_OPERATION('Must set WalletSigner services first.')
return this._services
}
getSettings(): table.Settings { return this.getActive().getSettings() }
async makeAvailable(): Promise<table.Settings> {
return await this.runAsWriter(async (writer) => {
writer.makeAvailable()
return writer.getSettings()
})
}
async migrate(storageName: string, storageIdentityKey: string): Promise<string> {
return await this.runAsWriter(async (writer) => {
return writer.migrate(storageName, storageIdentityKey)
})
}
async destroy(): Promise<void> {
return await this.runAsWriter(async (writer) => {
for (const store of this.stores)
await store.destroy()
})
}
async findOrInsertUser(identityKey: string): Promise<{ user: table.User, isNew: boolean }> {
const auth = await this.getAuth()
Iif (identityKey != auth.identityKey) throw new sdk.WERR_UNAUTHORIZED();
return await this.runAsWriter(async (writer) => {
const r = await writer.findOrInsertUser(identityKey)
Iif (auth.userId && auth.userId !== r.user.userId)
throw new sdk.WERR_INTERNAL('userId may not change for given identityKey')
this._authId.userId = r.user.userId
return r
})
}
async abortAction(args: AbortActionArgs): Promise<AbortActionResult> {
const vargs = sdk.validateAbortActionArgs(args)
const auth = await this.getAuth()
return await this.runAsWriter(async (writer) => {
return await writer.abortAction(auth, args)
})
}
async createAction(args: sdk.ValidCreateActionArgs): Promise<sdk.StorageCreateActionResult> {
const auth = await this.getAuth()
return await this.runAsWriter(async (writer) => {
return await writer.createAction(auth, args)
})
}
async internalizeAction(args: InternalizeActionArgs): Promise<InternalizeActionResult> {
const auth = await this.getAuth()
return await this.runAsWriter(async (writer) => {
return await writer.internalizeAction(auth, args)
})
}
async relinquishCertificate(args: RelinquishCertificateArgs): Promise<number> {
const vargs = sdk.validateRelinquishCertificateArgs(args)
const auth = await this.getAuth()
return await this.runAsWriter(async (writer) => {
return await writer.relinquishCertificate(auth, args)
})
}
async relinquishOutput(args: RelinquishOutputArgs): Promise<number> {
const vargs = sdk.validateRelinquishOutputArgs(args)
const auth = await this.getAuth()
return await this.runAsWriter(async (writer) => {
return await writer.relinquishOutput(auth, args)
})
}
async processAction(args: sdk.StorageProcessActionArgs): Promise<sdk.StorageProcessActionResults> {
const auth = await this.getAuth()
return await this.runAsWriter(async (writer) => {
return await writer.processAction(auth, args)
})
}
async insertCertificate(certificate: table.Certificate): Promise<number> {
const auth = await this.getAuth()
return await this.runAsWriter(async (writer) => {
return await writer.insertCertificateAuth(auth, certificate)
})
}
async listActions(args: ListActionsArgs): Promise<ListActionsResult> {
const vargs = sdk.validateListActionsArgs(args)
const auth = await this.getAuth()
return await this.runAsReader(async (reader) => {
return await reader.listActions(auth, args)
})
}
async listCertificates(args: sdk.ValidListCertificatesArgs): Promise<ListCertificatesResult> {
const auth = await this.getAuth()
return await this.runAsReader(async (reader) => {
return await reader.listCertificates(auth, args)
})
}
async listOutputs(args: ListOutputsArgs): Promise<ListOutputsResult> {
const vargs = sdk.validateListOutputsArgs(args)
const auth = await this.getAuth()
return await this.runAsReader(async (reader) => {
return await reader.listOutputs(auth, args)
})
}
async findCertificates(args: sdk.FindCertificatesArgs): Promise<table.Certificate[]> {
const auth = await this.getAuth()
return await this.runAsReader(async (reader) => {
return await reader.findCertificatesAuth(auth, args)
})
}
async findOutputBaskets(args: sdk.FindOutputBasketsArgs): Promise<table.OutputBasket[]> {
const auth = await this.getAuth()
return await this.runAsReader(async (reader) => {
return await reader.findOutputBasketsAuth(auth, args)
})
}
async findOutputs(args: sdk.FindOutputsArgs): Promise<table.Output[]> {
const auth = await this.getAuth()
return await this.runAsReader(async (reader) => {
return await reader.findOutputsAuth(auth, args)
})
}
async findProvenTxReqs(args: sdk.FindProvenTxReqsArgs): Promise<table.ProvenTxReq[]> {
return await this.runAsReader(async (reader) => {
return await reader.findProvenTxReqs(args)
})
}
async syncFromReader(identityKey: string, reader: StorageSyncReader): Promise<void> {
const auth = await this.getAuth()
Iif (identityKey !== auth.identityKey)
throw new sdk.WERR_UNAUTHORIZED()
const readerSettings = await reader.makeAvailable()
return await this.runAsSync(async (sync) => {
const writer = sync
const writerSettings = this.getSettings()
let log = ''
let inserts = 0, updates = 0
for (; ;) {
const ss = await entity.SyncState.fromStorage(writer, identityKey, readerSettings)
const args = ss.makeRequestSyncChunkArgs(identityKey, writerSettings.storageIdentityKey)
const chunk = await reader.getSyncChunk(args)
const r = await writer.processSyncChunk(args, chunk)
inserts += r.inserts
updates += r.updates
//log += `${r.maxUpdated_at} inserted ${r.inserts} updated ${r.updates}\n`
Iif (r.done)
break;
}
//console.log(log)
console.log(`sync complete: ${inserts} inserts, ${updates} updates`)
})
}
async updateBackups(activeSync?: sdk.WalletStorageSync) {
const auth = await this.getAuth()
return await this.runAsSync(async (sync) => {
for (const backup of this.stores.slice(1)) {
await this.syncToWriter(auth, backup, sync)
}
}, activeSync)
}
async syncToWriter(auth: sdk.AuthId, writer: sdk.WalletStorageProvider, activeSync?: sdk.WalletStorageSync): Promise<{ inserts: number, updates: number }> {
const identityKey = auth.identityKey
const writerSettings = await writer.makeAvailable()
return await this.runAsSync(async (sync) => {
const reader = sync
const readerSettings = this.getSettings()
let log = ''
let inserts = 0, updates = 0
for (; ;) {
const ss = await entity.SyncState.fromStorage(writer, identityKey, readerSettings)
const args = ss.makeRequestSyncChunkArgs(identityKey, writerSettings.storageIdentityKey)
const chunk = await reader.getSyncChunk(args)
const r = await writer.processSyncChunk(args, chunk)
inserts += r.inserts
updates += r.updates
log += `${r.maxUpdated_at} inserted ${r.inserts} updated ${r.updates}\n`
if (r.done)
break;
}
//console.log(log)
//console.log(`sync complete: ${inserts} inserts, ${updates} updates`)
return { inserts, updates }
}, activeSync)
}
/**
* Updates backups and switches to new active storage provider from among current backup providers.
*
* @param storageIdentityKey of current backup storage provider that is to become the new active provider.
*/
async setActive(storageIdentityKey: string): Promise<void> {
const newActiveIndex = this.stores.findIndex(s => s.getSettings().storageIdentityKey === storageIdentityKey)
Iif (newActiveIndex < 0)
throw new sdk.WERR_INVALID_PARAMETER('storageIdentityKey', `registered with this "WalletStorageManager" as a backup data store.`)
Iif (newActiveIndex === 0)
/** Setting the current active as the new active is a permitted no-op. */
return;
const auth = await this.getAuth()
const newActive = this.stores[newActiveIndex]
const newActiveStorageIdentityKey = (await newActive.makeAvailable()).storageIdentityKey
return await this.runAsSync(async (sync) => {
await sync.setActive(auth, newActiveStorageIdentityKey)
await this.updateBackups(sync)
// swap stores...
const oldActive = this.stores[0]
this.stores[0] = this.stores[newActiveIndex]
this.stores[newActiveIndex] = oldActive
this._authId = { ...this._authId, userId: undefined }
})
}
} |