Signed-off-by: James Zuccon <zuccon@gmail.com>
This commit is contained in:
James Zuccon
2024-09-06 10:59:30 +10:00
parent b9a53659ce
commit f189c4643b
12 changed files with 311 additions and 13 deletions
@@ -0,0 +1,125 @@
import { Transaction } from '@xo/primitives';
import { binToHex, Output } from '@bitauth/libauth';
export interface UTXO extends Output {
outpointTransactionHash: string;
outpointIndex: number;
}
export class TransactionGraph {
private transactions: Map<string, Transaction>;
constructor() {
this.transactions = new Map();
}
addTransaction(tx: Transaction) {
this.transactions.set(tx.toHashHex(), tx);
}
removeTransaction(txHash: string) {
this.transactions.delete(txHash);
}
getTransaction(txHash: string): Transaction | undefined {
return this.transactions.get(txHash);
}
getAllTransactions(): Transaction[] {
return Array.from(this.transactions.values());
}
deriveUtxoState(): UTXO[] {
const utxoMap = new Map<string, UTXO>();
// First, add all outputs as potential UTXOs
for (const tx of this.transactions.values()) {
tx.getOutputs().forEach((output, outpointIndex) => {
const txHashHex = tx.toHashHex();
const utxo: UTXO = {
outpointTransactionHash: txHashHex,
outpointIndex,
valueSatoshis: output.valueSatoshis,
lockingBytecode: output.lockingBytecode,
};
utxoMap.set(`${txHashHex}:${outpointIndex}`, utxo);
});
}
// Then, remove all spent outputs
for (const tx of this.transactions.values()) {
tx.getInputs().forEach((input) => {
const outpointTransactionHashHex = binToHex(
input.outpointTransactionHash
);
utxoMap.delete(`${outpointTransactionHashHex}:${input.outpointIndex}`);
});
}
return Array.from(utxoMap.values());
}
isTransactionValid(tx: Transaction): boolean {
const currentUtxos = this.deriveUtxoState();
const utxoMap = new Map(
currentUtxos.map((utxo) => [
`${utxo.outpointTransactionHash}:${utxo.outpointIndex}`,
utxo,
])
);
return tx.getInputs().every((input) => {
const outpointTransactionHashHex = binToHex(
input.outpointTransactionHash
);
return utxoMap.has(
`${outpointTransactionHashHex}:${input.outpointIndex}`
);
});
}
getDependentTransactions(txHash: string): Transaction[] {
return this.getAllTransactions().filter((tx) => {
tx.getInputs().some((input) => {
const outpointTransactionHashHex = binToHex(
input.outpointTransactionHash
);
return outpointTransactionHashHex === txHash;
});
});
}
getBroadcastOrder(): Transaction[] {
const visited = new Set<string>();
const order: Transaction[] = [];
const visit = (txid: string) => {
if (visited.has(txid)) return;
const tx = this.transactions.get(txid);
if (!tx) return;
visited.add(txid);
// First, visit all transactions that this transaction depends on
for (const input of tx.getInputs()) {
const outpointTransactionHashHex = binToHex(
input.outpointTransactionHash
);
visit(outpointTransactionHashHex);
}
order.push(tx);
};
// Start the topological sort from each transaction
for (const tx of this.transactions.values()) {
visit(tx.toHashHex());
}
return order;
}
}