All files / src/storage StorageProvider.ts

73.92% Statements 190/257
51.66% Branches 62/120
79.48% Functions 31/39
76.99% Lines 174/226

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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 54057x 57x 57x 57x 57x 57x 57x 57x 57x   57x   72x               6x                               72x 72x 72x 72x                                             43x   68x   27x   27x       3x 3x 3x 4x 2x 1x 1x 1x 1x 1x 1x 1x     1x     1x   1x       8x                           1x         1x 2x       2x 2x 2x 2x     2x 2x 2x   2x 2x     2x     2x   2x 2x       2x           2x 2x                 1x       14x 14x 14x 14x 14x 14x 16x 16x 16x 16x 12x       12x                                         4x     4x   4x 4x   4x 4x 4x 4x 4x 4x           4x                                                     14x   14x   14x 14x 14x 14x   14x             14x   9x   9x       1x 1x 1x     1x   1x             8x         9x           7x 7x     7x 7x       1x       9x                 25x 25x   25x         31x   31x 31x 13x     13x 13x 13x 13x       18x 18x     18x 18x 18x 18x 26x 26x 10x     10x     18x               6x               1x 1x 1x       1x 1x 1x 1x       46x 46x 46x 46x                                 5x   5x         5x 5x                       5x 5x 5x 5x 5x     5x   5x 5x 5x 5x 5x 5x 5x     5x 5x     5x       5x         5x                                                                                       28x 28x 28x 28x 28x 28x 28x 28x 28x   28x                                         57x 39x       39x 39x 39x   39x    
import { Transaction as BsvTransaction, AbortActionResult, Beef, InternalizeActionArgs, InternalizeActionResult, ListActionsArgs, ListActionsResult, ListOutputsArgs, ListOutputsResult, PubKeyHex, ListCertificatesResult, TrustSelf, RelinquishCertificateArgs, RelinquishOutputArgs } from '@bsv/sdk'
import { asArray, asString, entity, sdk, table, verifyId, verifyOne, verifyOneOrNone, verifyTruthy } from "../index.client";
import { getBeefForTransaction } from './methods/getBeefForTransaction';
import { GetReqsAndBeefDetail, GetReqsAndBeefResult, processAction } from './methods/processAction';
import { attemptToPostReqsToNetwork, PostReqsToNetworkResult } from './methods/attemptToPostReqsToNetwork';
import { listCertificates } from './methods/listCertificates';
import { createAction } from './methods/createAction';
import { internalizeAction } from './methods/internalizeAction';
import { StorageReaderWriter, StorageReaderWriterOptions } from './StorageReaderWriter';
 
export abstract class StorageProvider extends StorageReaderWriter implements sdk.WalletStorageProvider {
 
    isDirty = false
    _services?: sdk.WalletServices
    feeModel: sdk.StorageFeeModel
    commissionSatoshis: number
    commissionPubKeyHex?: PubKeyHex
    maxRecursionDepth?: number
 
    static defaultOptions() {
        return {
            feeModel: <sdk.StorageFeeModel>{ model: 'sat/kb', value: 1 },
            commissionSatoshis: 0,
            commissionPubKeyHex: undefined
        }
    }
 
    static createStorageBaseOptions(chain: sdk.Chain): StorageProviderOptions {
        const options: StorageProviderOptions = {
            ...StorageProvider.defaultOptions(),
            chain,
        }
        return options
    }
 
    constructor(options: StorageProviderOptions) {
        super(options)
        this.feeModel = options.feeModel
        this.commissionPubKeyHex = options.commissionPubKeyHex
        this.commissionSatoshis = options.commissionSatoshis
    }
 
    abstract purgeData(params: sdk.PurgeParams, trx?: sdk.TrxToken): Promise<sdk.PurgeResults>
 
    abstract allocateChangeInput(userId: number, basketId: number, targetSatoshis: number, exactSatoshis: number | undefined, excludeSending: boolean, transactionId: number): Promise<table.Output | undefined>
 
    abstract getProvenOrRawTx(txid: string, trx?: sdk.TrxToken): Promise<sdk.ProvenOrRawTx>
    abstract getRawTxOfKnownValidTransaction(txid?: string, offset?: number, length?: number, trx?: sdk.TrxToken): Promise<number[] | undefined>
 
    abstract getLabelsForTransactionId(transactionId?: number, trx?: sdk.TrxToken): Promise<table.TxLabel[]>
    abstract getTagsForOutputId(outputId: number, trx?: sdk.TrxToken): Promise<table.OutputTag[]>
 
    abstract listActions(auth: sdk.AuthId, args: ListActionsArgs): Promise<ListActionsResult>
    abstract listOutputs(auth: sdk.AuthId, args: ListOutputsArgs): Promise<ListOutputsResult>
 
    abstract countChangeInputs(userId: number, basketId: number, excludeSending: boolean): Promise<number>
 
    abstract findCertificatesAuth(auth: sdk.AuthId, args: sdk.FindCertificatesArgs ): Promise<table.Certificate[]>
    abstract findOutputBasketsAuth(auth: sdk.AuthId, args: sdk.FindOutputBasketsArgs ): Promise<table.OutputBasket[]>
    abstract findOutputsAuth(auth: sdk.AuthId, args: sdk.FindOutputsArgs ): Promise<table.Output[]>
    abstract insertCertificateAuth(auth: sdk.AuthId, certificate: table.CertificateX): Promise<number>
 
    override isStorageProvider(): boolean { return true }
 
    setServices(v: sdk.WalletServices) { this._services = v }
    getServices(): sdk.WalletServices {
        Iif (!this._services)
            throw new sdk.WERR_INVALID_OPERATION('Must set WalletSigner services first.')
        return this._services
    }
 
    async abortAction(auth: sdk.AuthId, args: Partial<table.Transaction>): Promise<AbortActionResult> {
        const r = await this.transaction(async trx => {
            const tx = verifyOneOrNone(await this.findTransactions({ partial: args, noRawTx: true, trx }))
            const unAbortableStatus: sdk.TransactionStatus[] = ['completed', 'failed', 'sending', 'unproven']
            if (!tx || !tx.isOutgoing || -1 < unAbortableStatus.findIndex(s => s === tx.status))
                throw new sdk.WERR_INVALID_PARAMETER('reference', 'an inprocess, outgoing action that has not been signed and shared to the network.');
            await this.updateTransactionStatus('failed', tx.transactionId, undefined, args.reference, trx)
            if (tx.txid) {
                const req = await entity.ProvenTxReq.fromStorageTxid(this, tx.txid, trx)
                if (req) {
                    req.addHistoryNote({ what: 'aborted' })
                    req.status = 'invalid'
                    await req.updateStorageDynamicProperties(this, trx)
                }
            }
            const r: AbortActionResult = {
                aborted: true
            }
            return r
        })
        return r
    }
 
    async internalizeAction(auth: sdk.AuthId, args: InternalizeActionArgs): Promise<InternalizeActionResult> {
        return await internalizeAction(this, auth, args)
    }
 
    /**
     * Given an array of transaction txids with current ProvenTxReq ready-to-share status,
     * lookup their DojoProvenTxReqApi req records.
     * For the txids with reqs and status still ready to send construct a single merged beef.
     * 
     * @param txids 
     * @param knownTxids 
     * @param trx 
     */
    async getReqsAndBeefToShareWithWorld(txids: string[], knownTxids: string[], trx?: sdk.TrxToken)
        : Promise<GetReqsAndBeefResult> {
        const r: GetReqsAndBeefResult = {
            beef: new Beef(),
            details: []
        }
 
        for (const txid of txids) {
            const d: GetReqsAndBeefDetail = {
                txid,
                status: 'unknown'
            }
            r.details.push(d)
            try {
                d.proven = verifyOneOrNone(await this.findProvenTxs({ partial: { txid }, trx }))
                Iif (d.proven)
                    d.status = 'alreadySent'
                else {
                    const alreadySentStatus = ['unmined', 'callback', 'unconfirmed', 'completed']
                    const readyToSendStatus = ['sending', 'unsent', 'nosend', 'unprocessed']
                    const errorStatus = ['unknown', 'nonfinal', 'invalid', 'doubleSpend']
 
                    d.req = verifyOneOrNone(await this.findProvenTxReqs({ partial: { txid }, trx }))
                    Iif (!d.req) {
                        d.status = 'error'
                        d.error = `ERR_UNKNOWN_TXID: ${txid} was not found.`
                    } else Iif (errorStatus.indexOf(d.req.status) > -1) {
                        d.status = 'error'
                        d.error = `ERR_INVALID_PARAMETER: ${txid} is not ready to send.`
                    } else Iif (alreadySentStatus.indexOf(d.req.status) > -1) {
                        d.status = 'alreadySent'
                    } else if (readyToSendStatus.indexOf(d.req.status) > -1) {
                        Iif (!d.req.rawTx || !d.req.inputBEEF) {
                            d.status = 'error'
                            d.error = `ERR_INTERNAL: ${txid} req is missing rawTx or beef.`
                        } else
                            d.status = 'readyToSend'
                    } else E{
                        d.status = 'error'
                        d.error = `ERR_INTERNAL: ${txid} has unexpected req status ${d.req.status}`
                    }
 
                    if (d.status === 'readyToSend') {
                        await this.mergeReqToBeefToShareExternally(d.req!, r.beef, knownTxids, trx);
                    }
                }
 
            } catch (eu: unknown) {
                const e = sdk.WalletError.fromUnknown(eu)
                d.error = `${e.name}: ${e.message}`
            }
        }
        return r
    }
 
    async mergeReqToBeefToShareExternally(req: table.ProvenTxReq, mergeToBeef: Beef, knownTxids: string[], trx?: sdk.TrxToken): Promise<void> {
        const { rawTx, inputBEEF: beef } = req;
        Iif (!rawTx || !beef) throw new sdk.WERR_INTERNAL(`req rawTx and beef must be valid.`);
        mergeToBeef.mergeRawTx(asArray(rawTx));
        mergeToBeef.mergeBeef(asArray(beef));
        const tx = BsvTransaction.fromBinary(asArray(rawTx));
        for (const input of tx.inputs) {
            Iif (!input.sourceTXID) throw new sdk.WERR_INTERNAL(`req all transaction inputs must have valid sourceTXID`);
            const txid = input.sourceTXID
            const btx = mergeToBeef.findTxid(txid);
            if (!btx) {
                Iif (knownTxids && knownTxids.indexOf(txid) > -1)
                    mergeToBeef.mergeTxidOnly(txid);
 
                else
                    await this.getValidBeefForKnownTxid(txid, mergeToBeef, undefined, knownTxids, trx);
            }
        }
    }
 
    /**
     * Checks if txid is a known valid ProvenTx and returns it if found.
     * Next checks if txid is a current ProvenTxReq and returns that if found.
     * If `newReq` is provided and an existing ProvenTxReq isn't found,
     * use `newReq` to create a new ProvenTxReq.
     * 
     * This is safe "findOrInsert" operation using retry if unique index constraint
     * is violated by a race condition insert.
     * 
     * @param txid 
     * @param newReq 
     * @param trx 
     * @returns 
     */
    async getProvenOrReq(txid: string, newReq?: table.ProvenTxReq, trx?: sdk.TrxToken)
        : Promise<sdk.StorageProvenOrReq> {
        Iif (newReq && txid !== newReq.txid)
            throw new sdk.WERR_INVALID_PARAMETER('newReq', `same txid`)
 
        const r: sdk.StorageProvenOrReq = { proven: undefined, req: undefined }
 
        r.proven = verifyOneOrNone(await this.findProvenTxs({ partial: { txid }, trx }))
        Iif (r.proven) return r
 
        for (let retry = 0; ; retry++) {
            try {
                r.req = verifyOneOrNone(await this.findProvenTxReqs({ partial: { txid }, trx }))
                Iif (r.req || !newReq) break;
                newReq.provenTxReqId = await this.insertProvenTxReq(newReq, trx)
                break;
            } catch (eu: unknown) {
                Iif (retry > 0) throw eu;
            }
        }
 
        return r
    }
 
    async updateTransactionsStatus(transactionIds: number[], status: sdk.TransactionStatus): Promise<void> {
        await this.transaction(async (trx) => {
            for (const id of transactionIds) {
                await this.updateTransactionStatus(status, id, undefined, undefined, trx)
            }
        })
    }
 
    /**
     * For all `status` values besides 'failed', just updates the transaction records status property.
     * 
     * For 'status' of 'failed', attempts to make outputs previously allocated as inputs to this transaction usable again.
     * 
     * @throws ERR_DOJO_COMPLETED_TX if current status is 'completed' and new status is not 'completed.
     * @throws ERR_DOJO_PROVEN_TX if transaction has proof or provenTxId and new status is not 'completed'. 
     * 
     * @param status 
     * @param transactionId 
     * @param userId 
     * @param reference 
     * @param trx 
     */
    async updateTransactionStatus(status: sdk.TransactionStatus, transactionId?: number, userId?: number, reference?: string, trx?: sdk.TrxToken)
        : Promise<void> {
        Iif (!transactionId && !(userId && reference)) throw new sdk.WERR_MISSING_PARAMETER('either transactionId or userId and reference')
 
        await this.transaction(async trx => {
 
            const where: Partial<table.Transaction> = {}
            if (transactionId) where.transactionId = transactionId
            Iif (userId) where.userId = userId
            if (reference) where.reference = reference
 
            const tx = verifyOne(await this.findTransactions({ partial: where, noRawTx: true, trx }))
 
            //if (tx.status === status)
            // no change required. Assume inputs and outputs spendable and spentBy are valid for status.
            //return
 
            // Once completed, this method cannot be used to "uncomplete" transaction.
            if (status !== 'completed' && tx.status === 'completed' || tx.provenTxId) throw new sdk.WERR_INVALID_OPERATION('The status of a "completed" transaction cannot be changed.')
            // It is not possible to un-fail a transaction. Information is lost and not recoverable. 
            Iif (status !== 'failed' && tx.status === 'failed') throw new sdk.WERR_INVALID_OPERATION(`A "failed" transaction may not be un-failed by this method.`)
 
            switch (status) {
                case 'failed': {
                    // Attempt to make outputs previously allocated as inputs to this transaction usable again.
                    // Only clear input's spentBy and reset spendable = true if it references this transaction
                    const t = new entity.Transaction(tx)
                    const inputs = await t.getInputs(this, trx)
                    for (const input of inputs) {
                        // input is a prior output belonging to userId that reference this transaction either by `spentBy`
                        // or by txid and vout.
                        await this.updateOutput(verifyId(input.outputId), { spendable: true, spentBy: undefined }, trx)
                    }
                } break;
                case 'nosend':
                case 'unsigned':
                case 'unprocessed':
                case 'sending':
                case 'unproven':
                case 'completed':
                    break;
                default:
                    throw new sdk.WERR_INVALID_PARAMETER('status', `not be ${status}`)
            }
 
            await this.updateTransaction(tx.transactionId, { status }, trx)
 
        }, trx)
    }
 
    async createAction(auth: sdk.AuthId, args: sdk.ValidCreateActionArgs): Promise<sdk.StorageCreateActionResult> {
        Iif (!auth.userId) throw new sdk.WERR_UNAUTHORIZED()
        return await createAction(this, auth, args)
    }
    async processAction(auth: sdk.AuthId, args: sdk.StorageProcessActionArgs): Promise<sdk.StorageProcessActionResults> {
        Iif (!auth.userId) throw new sdk.WERR_UNAUTHORIZED()
        return await processAction(this, auth, args)
    }
 
    async attemptToPostReqsToNetwork(reqs: entity.ProvenTxReq[], trx?: sdk.TrxToken): Promise<PostReqsToNetworkResult> {
        return await attemptToPostReqsToNetwork(this, reqs, trx)
    }
 
    async listCertificates(auth: sdk.AuthId, args: sdk.ValidListCertificatesArgs): Promise<ListCertificatesResult> {
        return await listCertificates(this, auth, args)
    }
 
    async verifyKnownValidTransaction(txid: string, trx?: sdk.TrxToken): Promise<boolean> {
        const { proven, rawTx } = await this.getProvenOrRawTx(txid, trx)
        return proven != undefined || rawTx != undefined
    }
 
    async getValidBeefForKnownTxid(txid: string, mergeToBeef?: Beef, trustSelf?: TrustSelf, knownTxids?: string[], trx?: sdk.TrxToken): Promise<Beef> {
        const beef = await this.getValidBeefForTxid(txid, mergeToBeef, trustSelf, knownTxids, trx)
        Iif (!beef)
            throw new sdk.WERR_INVALID_PARAMETER('txid', `${txid} is not known to storage.`)
        return beef
    }
 
    async getValidBeefForTxid(txid: string, mergeToBeef?: Beef, trustSelf?: TrustSelf, knownTxids?: string[], trx?: sdk.TrxToken): Promise<Beef | undefined> {
 
        const beef = mergeToBeef || new Beef()
 
        const r = await this.getProvenOrRawTx(txid, trx)
        if (r.proven) {
            Iif (trustSelf === 'known')
                beef.mergeTxidOnly(txid)
            else {
                beef.mergeRawTx(r.proven.rawTx)
                const mp = new entity.ProvenTx(r.proven).getMerklePath()
                beef.mergeBump(mp)
                return beef
            }
        }
 
        if (r.rawTx && r.inputBEEF) {
            Iif (trustSelf === 'known')
                beef.mergeTxidOnly(txid)
            else {
                beef.mergeRawTx(r.rawTx)
                beef.mergeBeef(r.inputBEEF)
                const tx = BsvTransaction.fromBinary(r.rawTx)
                for (const input of tx.inputs) {
                    const btx = beef.findTxid(input.sourceTXID!)
                    if (!btx) {
                        Iif (knownTxids && knownTxids.indexOf(input.sourceTXID!) > -1)
                            beef.mergeTxidOnly(input.sourceTXID!)
                        else
                            await this.getValidBeefForKnownTxid(input.sourceTXID!, beef, trustSelf, knownTxids, trx)
                    }
                }
                return beef
            }
        }
 
        return undefined
    }
 
    async getBeefForTransaction(txid: string, options: sdk.StorageGetBeefOptions): Promise<Beef> {
        return await getBeefForTransaction(this, txid, options)
    }
 
    async findMonitorEventById(id: number, trx?: sdk.TrxToken): Promise<table.MonitorEvent | undefined> {
        return verifyOneOrNone(await this.findMonitorEvents({ partial: { id }, trx }))
    }
 
    async relinquishCertificate(auth: sdk.AuthId, args: RelinquishCertificateArgs): Promise<number> {
        const vargs = sdk.validateRelinquishCertificateArgs(args)
        const cert = verifyOne(await this.findCertificates({ partial: { certifier: vargs.certifier, serialNumber: vargs.serialNumber, type: vargs.type } }))
        return await this.updateCertificate(cert.certificateId, { isDeleted: true })
    }
 
    async relinquishOutput(auth: sdk.AuthId, args: RelinquishOutputArgs): Promise<number> {
        const vargs = sdk.validateRelinquishOutputArgs(args)
        const { txid, vout } = sdk.parseWalletOutpoint(vargs.output)
        const output = verifyOne(await this.findOutputs({ partial: { txid, vout } }))
        return await this.updateOutput(output.outputId, { basketId: undefined })
    }
 
    async processSyncChunk(args: sdk.RequestSyncChunkArgs, chunk: sdk.SyncChunk): Promise<sdk.ProcessSyncChunkResult> {
        const user = verifyTruthy(await this.findUserByIdentityKey(args.identityKey))
        const ss = new entity.SyncState(verifyOne(await this.findSyncStates({ partial: { storageIdentityKey: args.fromStorageIdentityKey, userId: user.userId }})))
        const r = await ss.processSyncChunk(this, args, chunk)
        return r
    }
 
    /**
     * Handles storage changes when a valid MerklePath and mined block header are found for a ProvenTxReq txid.
     * 
     * Performs the following storage updates (typically):
     * 1. Lookup the exising `ProvenTxReq` record for its rawTx
     * 2. Insert a new ProvenTx record using properties from `args` and rawTx, yielding a new provenTxId
     * 3. Update ProvenTxReq record with status 'completed' and new provenTxId value (and history of status changed)
     * 4. Unpack notify transactionIds from req and update each transaction's status to 'completed', provenTxId value.
     * 5. Update ProvenTxReq history again to record that transactions have been notified.
     * 6. Return results...
     * 
     * Alterations of "typically" to handle:
     */
    async updateProvenTxReqWithNewProvenTx(args: sdk.UpdateProvenTxReqWithNewProvenTxArgs): Promise<sdk.UpdateProvenTxReqWithNewProvenTxResult> {
        const req = await entity.ProvenTxReq.fromStorageId(this, args.provenTxReqId)
        let proven: entity.ProvenTx
        Iif (req.provenTxId) {
            // Someone beat us to it, grab what we need for results...
            proven = new entity.ProvenTx(verifyOne(await this.findProvenTxs({ partial: { txid: args.txid }})))
        } else {
            let isNew: boolean
            ({ proven, isNew } = await this.transaction(async (trx) => {
                const { proven: api, isNew } = await this.findOrInsertProvenTx({
                    created_at: new Date(),
                    updated_at: new Date(),
                    provenTxId: 0,
                    txid: args.txid,
                    height: args.height,
                    index: args.index,
                    merklePath: args.merklePath,
                    rawTx: req.rawTx,
                    blockHash: args.blockHash,
                    merkleRoot: args.merkleRoot
                }, trx)
                proven = new entity.ProvenTx(api)
                if (isNew) {
                    req.status = 'completed'
                    req.provenTxId = proven.provenTxId
                    await req.updateStorageDynamicProperties(this, trx)
                    // upate the transaction notifications outside of storage transaction....
                }
                return { proven, isNew }
            }))
            if (isNew) {
                const ids = req.notify.transactionIds || []
                if (ids.length > 0) {
                    for (const id of ids) {
                        try {
                            await this.updateTransaction(id, { provenTxId: proven.provenTxId })
                            await this.updateTransactionStatus('completed', id)
                            req.addHistoryNote(`transaction ${id} notified of ProvenTx`)
                        } catch (eu: unknown) {
                            const e = sdk.WalletError.fromUnknown(eu)
                            req.addHistoryNote({ what: 'transactionNotificationFailure', error: `${e.code}: ${e.description}`})
                        }
                    }
                    await req.updateStorageDynamicProperties(this)
                }
            }
        }
        const r: sdk.UpdateProvenTxReqWithNewProvenTxResult = {
            status: req.status,
            history: req.apiHistory,
            provenTxId: proven.provenTxId
        }
        return r
    }
 
    /**
     * For each spendable output in the 'default' basket of the authenticated user,
     * verify that the output script, satoshis, vout and txid match that of an output
     * still in the mempool of at least one service provider.
     * 
     * @returns object with invalidSpendableOutputs array. A good result is an empty array. 
     */
    async confirmSpendableOutputs() : Promise<{ invalidSpendableOutputs: table.Output[] }> {
        const invalidSpendableOutputs: table.Output[] = []
        const users = await this.findUsers({ partial: {} })
        for (const { userId } of users) {
            const defaultBasket = verifyOne(await this.findOutputBaskets({ partial: { userId, name: 'default' } }))
            const where: Partial<table.Output> = {
                userId,
                basketId: defaultBasket.basketId,
                spendable: true,
            }
            const outputs = await this.findOutputs({ partial: where })
            for (let i = outputs.length - 1; i >= 0; i--) {
                const o = outputs[i]
                const oid = verifyId(o.outputId)
                Iif (o.spendable) {
                    let ok = false
                    Iif (o.lockingScript && o.lockingScript.length > 0) {
                        const r = await this.getServices().getUtxoStatus(asString(o.lockingScript), 'script')
                        Iif (r.status === 'success' && r.isUtxo && r.details?.length > 0) {
                            const tx = await this.findTransactionById(o.transactionId)
                            Iif (tx && tx.txid && r.details.some(d => d.txid === tx.txid && d.satoshis === o.satoshis && d.index === o.vout)) {
                                ok = true
                            }
                        }
                    }
                    Iif (!ok)
                        invalidSpendableOutputs.push(o)
                }
            }
        }
        return { invalidSpendableOutputs }
    }
 
    async updateProvenTxReqDynamics(id: number, update: Partial<table.ProvenTxReqDynamics>, trx?: sdk.TrxToken): Promise<number> {
        const partial: Partial<table.ProvenTxReq> = {}
        if (update['updated_at']) partial['updated_at'] = update['updated_at']
        if (update['provenTxId']) partial['provenTxId'] = update['provenTxId']
        if (update['status']) partial['status'] = update['status']
        if (update['attempts']) partial['attempts'] = update['attempts']
        Iif (update['notified']) partial['notified'] = update['notified']
        if (update['batch']) partial['batch'] = update['batch']
        if (update['history']) partial['history'] = update['history']
        if (update['notify']) partial['notify'] = update['notify']
 
        return await this.updateProvenTxReq(id, partial, trx)
    }
 
}
 
export interface StorageProviderOptions extends StorageReaderWriterOptions {
    chain: sdk.Chain
    feeModel: sdk.StorageFeeModel
    /**
     * Transactions created by this Storage can charge a fee per transaction.
     * A value of zero disables commission fees.
     */
    commissionSatoshis: number
    /**
     * If commissionSatoshis is greater than zero, must be a valid public key hex string.
     * The actual locking script for each commission will use a public key derived
     * from this key by information stored in the commissions table.
     */
    commissionPubKeyHex?: PubKeyHex
}
 
export function validateStorageFeeModel (v?: sdk.StorageFeeModel): sdk.StorageFeeModel {
  const r: sdk.StorageFeeModel = {
    model: 'sat/kb',
    value: 1
  }
  if (typeof v === 'object') {
    Iif (v.model !== 'sat/kb') throw new sdk.WERR_INVALID_PARAMETER('StorageFeeModel.model', `"sat/kb"`)
    if (typeof v.value === 'number') { r.value = v.value }
  }
  return r
}