Skip to content

Commit

Permalink
Cache transaction ids
Browse files Browse the repository at this point in the history
  • Loading branch information
Duddino committed Feb 26, 2024
1 parent 86f001f commit 48499c3
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
2 changes: 1 addition & 1 deletion scripts/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export class Database {
const store = this.#db
.transaction('txs', 'readwrite')
.objectStore('txs');
await store.put(tx, tx.txid);
await store.put(tx.__original, tx.txid);
}

/**
Expand Down
19 changes: 17 additions & 2 deletions scripts/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ export class Transaction {

/** @type{number[]} */
shieldData = [];
/** Cached txid */
#txid = '';

constructor({
version = 1,
Expand All @@ -98,10 +100,23 @@ export class Transaction {
this.blockTime = blockTime;
this.lockTime = lockTime;
this.shieldData = shieldData;
/** Handle to the unproxied tx for when we need to clone it */
this.__original = this;
return new Proxy(this, {
set(obj) {
obj.#txid = '';
return Reflect.set(...arguments);
},
});
}

get txid() {
return bytesToHex(dSHA256(hexToBytes(this.serialize())).reverse());
if (!this.__original.#txid) {
this.__original.#txid = bytesToHex(
dSHA256(hexToBytes(this.serialize())).reverse()
);
}
return this.__original.#txid;
}

isConfirmed() {
Expand Down Expand Up @@ -236,7 +251,7 @@ export class Transaction {
* Using the sighash type SIGHASH_ALL
*/
transactionHash(index) {
const copy = structuredClone(this);
const copy = structuredClone(this.__original);
// Black out all inputs
for (let i = 0; i < copy.vin.length; i++) {
if (i != index) copy.vin[i].scriptSig = '';
Expand Down
14 changes: 13 additions & 1 deletion tests/unit/transaction.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, test, vi, beforeAll } from 'vitest';
import { describe, it, test, vi, beforeAll, expect } from 'vitest';
import {
Transaction,
CTxIn,
Expand Down Expand Up @@ -78,6 +78,18 @@ describe('transaction tests', () => {
expect(ourTx).toStrictEqual(tx);
});

it.sequential('updates txid when a property changes', () => {
const [tx, txid] = testVector[0];
const originalVersion = tx.version;
expect(tx.txid).toBe(txid);
tx.version = 10;
expect(tx.txid).not.toBe(txid);
expect(tx.txid).toBe(
'416368b2101fab865db162d49d0540560f802e89801cad8eb1d9cf3a4e6ad5be'
);
tx.version = originalVersion;
});

it.each(testVector.filter((t) => t[3]))(
'signs correctly ($txid)',
async (tx, _, hex, inputs) => {
Expand Down

0 comments on commit 48499c3

Please sign in to comment.