All files / src/storage/schema/entities ProvenTxReq.ts

86.69% Statements 189/218
64.07% Branches 66/103
98.46% Functions 64/65
89.39% Lines 177/198

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  57x 57x       57x   21x 21x 21x       5x 5x 5x       10x 10x                                     172x     168x       317x     310x       5x 5x     1x 1x       5x 5x     1x 1x       167x 167x       309x 309x 309x   289x 289x 288x   289x         5x 5x 5x       304x 304x                           304x 304x 304x             10x 10x 10x 10x 45x   10x       10x 10x 10x 10x 10x 10x   10x 10x 10x       1x               1x 1x 1x 2x     1x       17x               17x 17x 16x     1x 1x         1x         9x 9x   8x 8x                     1x 1x             9x           5x         6x       122x 122x 122x 122x 122x       197x 197x 60x 197x 197x 197x 197x     177x 177x   197x                   1x 1x 1x 1x   1x 1x                 28x 28x 28x                   28x 23x 23x   5x 5x 5x           7x 7x 7x 7x 7x                 7x             52x     28x 28x         28x       1x     133x     1x     1x     1x     75x     78x     1x     1x     1x     63x     1x     55x     13x     114x     38x     1x     128x     103x     3x       193x     1x     1x     1x             2x   2x 1x 1x                                               1x       110x 110x                 66x 66x 66x 66x 66x 66x             46x 46x 46x 46x 46x 46x 46x               46x 46x 46x 137x           6x       66x 66x 66x 66x                               45x 45x   45x 45x   45x 45x 45x                                                
import { MerklePath } from '@bsv/sdk'
import { arraysEqual, asString, entity, sdk, StorageProvider, table, verifyId, verifyOne, verifyOneOrNone, verifyTruthy, WalletStorageManager } from '../../../index.client'
import { EntityBase } from '.'
 
import { StorageProcessActionArgs } from '../../../sdk'
 
export class ProvenTxReq extends EntityBase<table.ProvenTxReq> {
  static async fromStorageTxid(storage: entity.EntityStorage, txid: string, trx?: sdk.TrxToken): Promise<ProvenTxReq | undefined> {
    const reqApi = verifyOneOrNone(await storage.findProvenTxReqs({ partial: { txid }, trx }))
    Iif (!reqApi) return undefined
    return new ProvenTxReq(reqApi)
  }
 
  static async fromStorageId(storage: entity.EntityStorage, id: number, trx?: sdk.TrxToken): Promise<ProvenTxReq> {
    const reqApi = verifyOneOrNone(await storage.findProvenTxReqs({ partial: { provenTxReqId: id }, trx }))
    Iif (!reqApi) throw new sdk.WERR_INTERNAL(`proven_tx_reqs with id ${id} is missing.`)
    return new ProvenTxReq(reqApi)
  }
 
  static fromTxid(txid: string, rawTx: number[], inputBEEF?: number[]): ProvenTxReq {
    const now = new Date()
    return new ProvenTxReq({
      provenTxReqId: 0,
      created_at: now,
      updated_at: now,
      txid,
      inputBEEF,
      rawTx,
      status: 'unknown',
      history: '{}',
      notify: '{}',
      attempts: 0,
      notified: false
    })
  }
 
  history: ProvenTxReqHistory
  notify: ProvenTxReqNotify
 
  packApiHistory() {
    this.api.history = JSON.stringify(this.history)
  }
  packApiNotify() {
    this.api.notify = JSON.stringify(this.notify)
  }
 
  unpackApiHistory() {
    this.history = JSON.parse(this.api.history)
  }
  unpackApiNotify() {
    this.notify = JSON.parse(this.api.notify)
  }
 
  get apiHistory(): string {
    this.packApiHistory()
    return this.api.history
  }
  get apiNotify(): string {
    this.packApiNotify()
    return this.api.notify
  }
 
  set apiHistory(v: string) {
    this.api.history = v
    this.unpackApiHistory()
  }
  set apiNotify(v: string) {
    this.api.notify = v
    this.unpackApiNotify()
  }
 
  updateApi(): void {
    this.packApiHistory()
    this.packApiNotify()
  }
 
  unpackApi(): void {
    this.unpackApiHistory()
    this.unpackApiNotify()
    if (this.notify.transactionIds) {
      // Cleanup null values and duplicates.
      const transactionIds: number[] = []
      for (const id of this.notify.transactionIds) {
        if (Number.isInteger(id) && !transactionIds.some(txid => txid === id)) transactionIds.push(id)
      }
      this.notify.transactionIds = transactionIds
    }
  }
 
  async refreshFromStorage(storage: entity.EntityStorage | WalletStorageManager): Promise<void> {
    const newApi = verifyOne(await storage.findProvenTxReqs({ partial: { provenTxReqId: this.id } }))
    this.api = newApi
    this.unpackApi()
  }
 
  constructor(api?: table.ProvenTxReq) {
    const now = new Date()
    super(
      api || {
        provenTxReqId: 0,
        created_at: now,
        updated_at: now,
        txid: '',
        rawTx: [],
        history: '',
        notify: '',
        attempts: 0,
        status: 'unknown',
        notified: false
      }
    )
    this.history = {}
    this.notify = {}
    this.unpackApi()
  }
 
  /**
   * Returns history to only what followed since date.
   */
  historySince(since: Date): ProvenTxReqHistory {
    const fh: ProvenTxReqHistory = { notes: {} }
    const filter = since.toISOString()
    const notes = this.history.notes
    if (notes && fh.notes) {
      for (const key of Object.keys(notes)) if (key > filter) fh.notes[key] = notes[key]
    }
    return fh
  }
 
  historyPretty(since?: Date, indent = 0): string {
    const h = since ? this.historySince(since) : { ...this.history }
    Iif (!h.notes) return ''
    const keyLimit = since ? since.toISOString() : undefined
    for (const key of Object.keys(h.notes)) {
      Iif (keyLimit && key < keyLimit) continue
      h.notes[key] = this.parseHistoryNote(h.notes[key])
    }
    let log = ''
    if (log.slice(-1) !== '\n') log += '\n'
    return log
  }
 
  getHistorySummary(): ProvenTxReqHistorySummaryApi {
    const summary: ProvenTxReqHistorySummaryApi = {
      setToCompleted: false,
      setToUnmined: false,
      setToCallback: false,
      setToDoubleSpend: false,
      setToSending: false,
      setToUnconfirmed: false
    }
    const h = this.history
    if (h.notes) {
      for (const key of Object.keys(h.notes)) {
        this.parseHistoryNote(h.notes[key], summary)
      }
    }
    return summary
  }
 
  parseHistoryNote(note: string, summary?: ProvenTxReqHistorySummaryApi): string {
    const c = summary || {
      setToCompleted: false,
      setToUnmined: false,
      setToCallback: false,
      setToDoubleSpend: false,
      setToSending: false,
      setToUnconfirmed: false
    }
    try {
      const v = JSON.parse(note)
      switch (v.what) {
        case 'postReqsToNetwork result':
          {
            const r = v['result'] as any
            return `posted by ${v['name']} status=${r.status} txid=${r.txid}`
          }
          break
        case 'getMerkleProof invalid':
          {
            return `getMerkleProof failing after ${v['attempts']} attempts over ${v['ageInMinutes']} minutes`
          }
          break
        case 'ProvenTxReq.set status':
          {
            const status: sdk.ProvenTxReqStatus = v.new
            switch (status) {
              case 'completed':
                c.setToCompleted = true
                break
              case 'unmined':
                c.setToUnmined = true
                break
              case 'callback':
                c.setToCallback = true
                break
              case 'doubleSpend':
                c.setToDoubleSpend = true
                break
              case 'sending':
                c.setToSending = true
                break
              case 'unconfirmed':
                c.setToUnconfirmed = true
                break
              default:
                break
            }
            return `set status ${v.old} to ${v.new}`
          }
          break
        case 'notified':
          return `notified`
        default:
          break
      }
    } catch {
      /** */
    }
    return note
  }
 
  addNotifyTransactionId(id: number) {
    Iif (!Number.isInteger(id)) throw new sdk.WERR_INVALID_PARAMETER('id', 'integer')
    const s = new Set(this.notify.transactionIds || [])
    s.add(id)
    this.notify.transactionIds = [...s].sort((a, b) => (a > b ? 1 : a < b ? -1 : 0))
    this.notified = false
  }
 
  addHistoryNote<T extends { what: string }>(note: string | T, when?: Date) {
    if (!this.history.notes) this.history.notes = {}
    if (typeof note === 'string') note = JSON.stringify({ what: 'string', note })
    else note = JSON.stringify(note)
    when ||= new Date()
    let msecs = when.getTime()
    let key = when.toISOString()
    while (this.history.notes[key]) {
      // Make sure new key (timestamp) will not overwrite existing.
      // Fudge the time by 1 msec forward until unique
      msecs += 1
      key = new Date(msecs).toISOString()
    }
    this.history.notes[key] = note
  }
 
  /**
     * Updates database record with current state of this entity.
 
     * @param storage 
     * @param trx 
     */
  async updateStorage(storage: entity.EntityStorage, trx?: sdk.TrxToken) {
    this.updated_at = new Date()
    this.updateApi()
    if (this.id === 0) {
      await storage.insertProvenTxReq(this.api)
    }
    const update: Partial<table.ProvenTxReq> = { ...this.api }
    await storage.updateProvenTxReq(this.id, update, trx)
  }
 
  /**
   * Update storage with changes to only status and history.
   * @param storage
   * @param trx
   */
  async updateStorageDynamicProperties(storage: WalletStorageManager | StorageProvider, trx?: sdk.TrxToken) {
    this.updated_at = new Date()
    this.updateApi()
    const update: Partial<table.ProvenTxReqDynamics> = {
      updated_at: this.api.updated_at,
      provenTxId: this.api.provenTxId,
      status: this.api.status,
      history: this.api.history,
      notify: this.api.notify,
      notified: this.api.notified,
      attempts: this.api.attempts,
      batch: this.api.batch
    }
    if (storage.isStorageProvider()) {
      const sp = storage as StorageProvider
      await sp.updateProvenTxReqDynamics(this.id, update, trx)
    } else {
      const wsm = storage as WalletStorageManager
      await wsm.runAsStorageProvider(async sp => {
        await sp.updateProvenTxReqDynamics(this.id, update, trx)
      })
    }
  }
 
  async insertOrMerge(storage: entity.EntityStorage, trx?: sdk.TrxToken): Promise<ProvenTxReq> {
    const req = await storage.transaction<ProvenTxReq>(async trx => {
      let reqApi0 = this.toApi()
      const { req: reqApi1, isNew } = await storage.findOrInsertProvenTxReq(reqApi0, trx)
      if (isNew) {
        return new entity.ProvenTxReq(reqApi1)
      } else E{
        const req = new ProvenTxReq(reqApi1)
        req.mergeNotifyTransactionIds(reqApi0)
        req.mergeHistory(reqApi0)
        await req.updateStorage(storage, trx)
        return req
      }
    }, trx)
    return req
  }
 
  /**
   * See `DojoProvenTxReqStatusApi`
   */
  get status() {
    return this.api.status
  }
  set status(v: sdk.ProvenTxReqStatus) {
    if (v !== this.api.status) {
      this.addHistoryNote({
        what: 'ProvenTxReq.set status',
        old: this.api.status,
        new: v
      })
      this.api.status = v
    }
  }
  get provenTxReqId() {
    return this.api.provenTxReqId
  }
  set provenTxReqId(v: number) {
    this.api.provenTxReqId = v
  }
  get created_at() {
    return this.api.created_at
  }
  set created_at(v: Date) {
    this.api.created_at = v
  }
  get updated_at() {
    return this.api.updated_at
  }
  set updated_at(v: Date) {
    this.api.updated_at = v
  }
  get txid() {
    return this.api.txid
  }
  set txid(v: string) {
    this.api.txid = v
  }
  get inputBEEF() {
    return this.api.inputBEEF
  }
  set inputBEEF(v: number[] | undefined) {
    this.api.inputBEEF = v
  }
  get rawTx() {
    return this.api.rawTx
  }
  set rawTx(v: number[]) {
    this.api.rawTx = v
  }
  get attempts() {
    return this.api.attempts
  }
  set attempts(v: number) {
    this.api.attempts = v
  }
  get provenTxId() {
    return this.api.provenTxId
  }
  set provenTxId(v: number | undefined) {
    this.api.provenTxId = v
  }
  get notified() {
    return this.api.notified
  }
  set notified(v: boolean) {
    this.api.notified = v
  }
  get batch() {
    return this.api.batch
  }
  set batch(v: string | undefined) {
    this.api.batch = v
  }
 
  override get id() {
    return this.api.provenTxReqId
  }
  override set id(v: number) {
    this.api.provenTxReqId = v
  }
  override get entityName(): string {
    return 'ProvenTxReq'
  }
  override get entityTable(): string {
    return 'proven_tx_reqs'
  }
 
  /**
   * 'convergent' equality must satisfy (A sync B) equals (B sync A)
   */
  override equals(ei: table.ProvenTxReq, syncMap?: entity.SyncMap | undefined): boolean {
    const eo = this.toApi()
 
    if (eo.txid != ei.txid || !arraysEqual(eo.rawTx, ei.rawTx) || (!eo.inputBEEF && ei.inputBEEF) || (eo.inputBEEF && !ei.inputBEEF) || (eo.inputBEEF && ei.inputBEEF && !arraysEqual(eo.inputBEEF, ei.inputBEEF)) || eo.batch != ei.batch) return false
    if (syncMap) {
      Iif (
        // attempts doesn't matter for convergent equality
        // history doesn't matter for convergent equality
        // only local transactionIds matter, that cared about this txid in sorted order
        eo.provenTxReqId !== syncMap.provenTxReq.idMap[verifyId(ei.provenTxReqId)] ||
        (!eo.provenTxId && ei.provenTxId) ||
        (eo.provenTxId && !ei.provenTxId) ||
        (ei.provenTxId && eo.provenTxId !== syncMap.provenTx.idMap[ei.provenTxId])
        // || eo.created_at !== minDate(ei.created_at, eo.created_at)
        // || eo.updated_at !== maxDate(ei.updated_at, eo.updated_at)
      )
        return false
    } else E{
      Iif (
        eo.attempts != ei.attempts ||
        eo.history != ei.history ||
        eo.notify != ei.notify ||
        eo.provenTxReqId !== ei.provenTxReqId ||
        eo.provenTxId !== ei.provenTxId
        // || eo.created_at !== ei.created_at
        // || eo.updated_at !== ei.updated_at
      )
        return false
    }
    return true
  }
 
  static async mergeFind(storage: entity.EntityStorage, userId: number, ei: table.ProvenTxReq, syncMap: entity.SyncMap, trx?: sdk.TrxToken): Promise<{ found: boolean; eo: ProvenTxReq; eiId: number }> {
    const ef = verifyOneOrNone(await storage.findProvenTxReqs({ partial: { txid: ei.txid }, trx }))
    return {
      found: !!ef,
      eo: new ProvenTxReq(ef || { ...ei }),
      eiId: verifyId(ei.provenTxReqId)
    }
  }
 
  mapNotifyTransactionIds(syncMap: entity.SyncMap): void {
    // Map external notification transaction ids to local ids
    const externalIds = this.notify.transactionIds || []
    this.notify.transactionIds = []
    for (const transactionId of externalIds) {
      const localTxId: number | undefined = syncMap.transaction.idMap[transactionId]
      if (localTxId) {
        this.addNotifyTransactionId(localTxId)
      }
    }
  }
 
  mergeNotifyTransactionIds(ei: table.ProvenTxReq, syncMap?: entity.SyncMap): void {
    // Map external notification transaction ids to local ids and merge them if they exist.
    const eie = new ProvenTxReq(ei)
    if (eie.notify.transactionIds) {
      this.notify.transactionIds ||= []
      for (const transactionId of eie.notify.transactionIds) {
        const localTxId: number | undefined = syncMap ? syncMap.transaction.idMap[transactionId] : transactionId
        if (localTxId) {
          this.addNotifyTransactionId(localTxId)
        }
      }
    }
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  mergeHistory(ei: table.ProvenTxReq, syncMap?: entity.SyncMap): void {
    const eie = new ProvenTxReq(ei)
    if (eie.history.notes) {
      for (const [k, v] of Object.entries(eie.history.notes)) {
        this.addHistoryNote(v, new Date(k))
      }
    }
  }
 
  static isTerminalStatus(status: sdk.ProvenTxReqStatus): boolean {
    return sdk.ProvenTxReqTerminalStatus.some(s => s === status)
  }
 
  override async mergeNew(storage: entity.EntityStorage, userId: number, syncMap: entity.SyncMap, trx?: sdk.TrxToken): Promise<void> {
    if (this.provenTxId) this.provenTxId = syncMap.provenTx.idMap[this.provenTxId]
    this.mapNotifyTransactionIds(syncMap)
    this.provenTxReqId = 0
    this.provenTxReqId = await storage.insertProvenTxReq(this.toApi(), trx)
  }
 
  /**
   * When merging `ProvenTxReq`, care is taken to avoid short-cirtuiting notification: `status` must not transition to `completed` without
   * passing through `notifying`. Thus a full convergent merge passes through these sequence steps:
   * 1. Remote dojo completes before local dojo.
   * 2. The remotely completed req and ProvenTx sync to local dojo.
   * 3. The local dojo transitions to `notifying`, after merging the remote attempts and history.
   * 4. The local dojo notifies, transitioning to `completed`.
   * 5. Having been updated, the local req, but not ProvenTx sync to remote dojo, but do not merge because the earlier `completed` wins.
   * 6. Convergent equality is achieved (completing work - history and attempts are equal)
   *
   * On terminal failure: `doubleSpend` trumps `invalid` as it contains more data.
   */
  override async mergeExisting(storage: entity.EntityStorage, since: Date | undefined, ei: table.ProvenTxReq, syncMap: entity.SyncMap, trx?: sdk.TrxToken): Promise<boolean> {
    Iif (!this.batch && ei.batch) this.batch = ei.batch
    else Iif (this.batch && ei.batch && this.batch !== ei.batch) throw new sdk.WERR_INTERNAL('ProvenTxReq merge batch not equal.')
 
    this.mergeHistory(ei, syncMap)
    this.mergeNotifyTransactionIds(ei, syncMap)
 
    this.updated_at = new Date()
    await storage.updateProvenTxReq(this.id, this.toApi(), trx)
    return false
  }
}
 
export interface ProvenTxReqHistorySummaryApi {
  setToCompleted: boolean
  setToCallback: boolean
  setToUnmined: boolean
  setToDoubleSpend: boolean
  setToSending: boolean
  setToUnconfirmed: boolean
}
 
export interface ProvenTxReqHistory {
  /**
   * Keys are Date().toISOString()
   * Values are a description of what happened.
   */
  notes?: Record<string, string>
}
 
export interface ProvenTxReqNotify {
  transactionIds?: number[]
}