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

85.26% Statements 81/95
68.62% Branches 35/51
100% Functions 35/35
88.5% Lines 77/87

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 25757x 57x 57x   57x                                         3x   3x   3x 3x 3x   2x 1x     1x   1x 1x 1x 1x                       1x       1x       914x 914x                                       13x       23x 1051x 2x 1x 2x 1x 3x 1x 3x 1x 2x 1x 3x 1x 2x 1x 3x 1x 3x 1x   876x 1x 1x 1x     6x 6x                       3x 3x 2x 1x   1x 1x   1x         875x 875x               525x   525x         351x           57x         57x                                   10x 10x   10x   10x   10x     5x     5x                               5x     5x   5x   5x 5x 8x 5x   5x                         5x                                  
import { MerklePath } from "@bsv/sdk"
import { arraysEqual, entity, sdk, table, verifyId, verifyOneOrNone } from "../../../index.client";
import { EntityBase } from ".";
 
export class ProvenTx extends EntityBase<table.ProvenTx> {
    
    /**
     * Given a txid and optionally its rawTx, create a new ProvenTx object.
     * 
     * rawTx is fetched if not provided.
     * 
     * Only succeeds (proven is not undefined) if a proof is confirmed for rawTx,
     * and hash of rawTx is confirmed to match txid
     * 
     * The returned ProvenTx and ProvenTxReq objects have not been added to the dojo database,
     * this is optional and can be done by the caller if appropriate.
     * 
     * @param txid 
     * @param services 
     * @param rawTx 
     * @returns 
     */
    static async fromTxid(txid: string, services: sdk.WalletServices, rawTx?: number[])
    : Promise<ProvenTxFromTxidResult> {
 
        const r: ProvenTxFromTxidResult = { proven: undefined, rawTx }
 
        const chain = services.chain
 
        if (!r.rawTx) {
          const gr = await services.getRawTx(txid)
          if (!gr?.rawTx)
            // Failing to find anything...
            return r
          r.rawTx = gr.rawTx!
        }
 
        const gmpr = await services.getMerklePath(txid)
 
        if (gmpr.merklePath && gmpr.header) {
            const index = gmpr.merklePath.path[0].find(l => l.hash === txid)?.offset
            if (index !== undefined) {
                const api: table.ProvenTx = {
                    created_at: new Date(),
                    updated_at: new Date(),
                    provenTxId: 0,
                    txid,
                    height: gmpr.header.height,
                    index,
                    merklePath: gmpr.merklePath.toBinary(),
                    rawTx: r.rawTx,
                    blockHash: gmpr.header.hash,
                    merkleRoot: gmpr.header.merkleRoot
                }
                r.proven = new ProvenTx(api)
            }
        }
 
        return r
    }
 
    constructor(api?: table.ProvenTx) {
        const now = new Date()
        super(api || {
            provenTxId: 0,
            created_at: now,
            updated_at: now,
            txid: '',
            height: 0,
            index: 0,
            merklePath: [],
            rawTx: [],
            blockHash: '',
            merkleRoot: ''
        })
    }
    override updateApi(): void {
        /* nothing needed yet... */
    }
   
    /**
     * @returns desirialized `MerklePath` object, value is cached.
     */
    getMerklePath() : MerklePath { if (!this._mp) this._mp = MerklePath.fromBinary(this.api.merklePath); return this._mp }
    _mp?: MerklePath
 
       
    get provenTxId() { return this.api.provenTxId }
    set provenTxId(v: number) { this.api.provenTxId = 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 height() { return this.api.height }
    set height(v: number) { this.api.height = v }
    get index() { return this.api.index }
    set index(v: number) { this.api.index = v }
    get merklePath() { return this.api.merklePath }
    set merklePath(v: number[]) { this.api.merklePath = v }
    get rawTx() { return this.api.rawTx }
    set rawTx(v: number[]) { this.api.rawTx = v }
    get blockHash() { return this.api.blockHash }
    set blockHash(v: string) { this.api.blockHash = v }
    get merkleRoot() { return this.api.merkleRoot }
    set merkleRoot(v: string) { this.api.merkleRoot = v }
 
    override get id() { return this.api.provenTxId }
    override set id(v: number) { this.api.provenTxId = v }
    override get entityName(): string { return 'ProvenTx' }
    override get entityTable(): string { return 'proven_txs' }
 
    override equals(ei: table.ProvenTx, syncMap?: entity.SyncMap | undefined): boolean {
        const eo = this.toApi()
        if (
            eo.txid != ei.txid ||
            eo.height != ei.height ||
            eo.index != ei.index ||
            !arraysEqual(eo.merklePath,ei.merklePath) ||
            !arraysEqual(eo.rawTx, ei.rawTx) ||
            eo.blockHash !== ei.blockHash ||
            eo.merkleRoot !== ei.merkleRoot
            // equality does not depend on timestamps.
            // || eo.created_at !== ei.created_at
            // || eo.updated_at !== ei.updated_at
            )
            return false
        if (syncMap) {
            if (eo.provenTxId !== syncMap.provenTx.idMap[ei.provenTxId])
                return false
        } else {
            if ( eo.provenTxId !== ei.provenTxId)
                return false
        }
        return true
    }
 
    static async mergeFind(storage: entity.EntityStorage, userId: number, ei: table.ProvenTx, syncMap: entity.SyncMap, trx?: sdk.TrxToken)
    : Promise<{ found: boolean, eo: entity.ProvenTx, eiId: number }> {
        const ef = verifyOneOrNone(await storage.findProvenTxs({ partial: { txid: ei.txid }, trx }))
        return {
            found: !!ef,
            eo: new ProvenTx(ef || { ...ei }),
            eiId: verifyId(ei.provenTxId)
        }
    }
 
    override async mergeNew(storage: entity.EntityStorage, userId: number, syncMap: entity.SyncMap, trx?: sdk.TrxToken): Promise<void> {
        this.provenTxId = 0
        // TODO: Since these records are a shared resource, the record must be validated before accepting it...
        this.provenTxId = await storage.insertProvenTx(this.toApi(), trx)
    }
 
    override async mergeExisting(storage: entity.EntityStorage, since: Date | undefined, ei: table.ProvenTx, syncMap: entity.SyncMap, trx?: sdk.TrxToken): Promise<boolean> {
        // ProvenTxs are never updated.
        return false
    }
 
    /**
     * How high attempts can go before status is forced to invalid
     */
    static getProofAttemptsLimit = 8
 
    /**
     * How many hours we have to try for a poof
     */
    static getProofMinutes = 60
 
    /**
     * Try to create a new ProvenTx from a ProvenTxReq and GetMerkleProofResultApi
     * 
     * Otherwise it returns undefined and updates req.status to either 'unknown', 'invalid', or 'unconfirmed'
     * 
     * @param req 
     * @param gmpResult 
     * @returns 
     */
    static async fromReq(
        req: entity.ProvenTxReq,
        gmpResult: sdk.GetMerklePathResult,
        countsAsAttempt: boolean
    )
    : Promise<ProvenTx | undefined>
    {
        Iif (!req.txid) throw new sdk.WERR_MISSING_PARAMETER('req.txid')
        Iif (!req.rawTx) throw new sdk.WERR_MISSING_PARAMETER('req.rawTx')
 
        Iif (!req.rawTx) throw new sdk.WERR_INTERNAL('rawTx must be valid')
 
        req.addHistoryNote({ what: 'getMerkleProof result', result: gmpResult, attempts: req.attempts })
 
        if (!gmpResult.name && !gmpResult.merklePath && !gmpResult.error) {
            // Most likely offline or now services configured.
            // Does not count as a proof attempt.
            return undefined
        }
 
        Iif (!gmpResult.merklePath) {
 
            Iif (req.created_at) {
                const reqAgeInMsecs = Date.now() - req.created_at.getTime()
                const reqAgeInMinutes = Math.ceil(reqAgeInMsecs < 1 ? 0 : reqAgeInMsecs / (1000 * 60))
 
                Iif (req.attempts > entity.ProvenTx.getProofAttemptsLimit && reqAgeInMinutes > entity.ProvenTx.getProofMinutes) {
                    // Start the process of setting transactions to 'failed'
                    req.addHistoryNote({ what: 'getMerkleProof invalid', attempts: req.attempts, ageInMinutes: reqAgeInMinutes })
                    req.notified = false
                    req.status = 'invalid'
                }
            }
            return undefined
        }
 
        Iif (countsAsAttempt)
            req.attempts++
        
        const merklePaths = (Array.isArray(gmpResult.merklePath)) ? gmpResult.merklePath : [gmpResult.merklePath]
 
        for (const proof of merklePaths) {
 
            try {
                const now = new Date()
                const leaf = proof.path[0].find(leaf => leaf.txid === true && leaf.hash === req.txid)
                Iif (!leaf) throw new sdk.WERR_INTERNAL('merkle path does not contain leaf for txid')
 
                const proven = new ProvenTx({
                    created_at: now,
                    updated_at: now,
                    provenTxId: 0,
                    txid: req.txid,
                    height: proof.blockHeight,
                    index: leaf.offset,
                    merklePath: proof.toBinary(),
                    rawTx: req.rawTx,
                    merkleRoot: gmpResult.header!.merkleRoot,
                    blockHash: gmpResult.header!.hash
                })
 
                return proven
 
            } catch (err: unknown) {
                req.addHistoryNote({
                    what: "getMerkleProof catch",
                    proof,
                    error: sdk.WalletError.fromUnknown(err)
                })
            }
        }
    }
    
}
 
export interface ProvenTxFromTxidResult {
    proven?: entity.ProvenTx
    rawTx?: number[]
}