E317 feat: decode transactions by oritwoen · Pull Request #430 · agntn/keys · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/utils/transaction/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
export { extractSignatures } from "./signatures.ts";
export { decode } from "./transaction.ts";
export type { Transaction, TransactionInput, TransactionOutput } from "./transaction.ts";
export type { InputSignature, SignatureExtractionOptions, SpentOutput } from "./signatures.ts";
export { recoverSigner } from "./evm.ts";
export type { EvmAccessListEntry, EvmTransactionJson, TransactionSigner } from "./evm.ts";
34 changes: 3 additions & 31 deletions src/utils/transaction/signatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import { assertOptions } from "../options.ts";
import { pushOf, scriptOperations, scriptPushes } from "./script.ts";
import { legacySighash, segwitSighash, taprootSighash } from "./sighash.ts";
import {
decodeTransaction,
decode,
decodeHex,
type Transaction,
type TransactionInput,
type TransactionOutput,
Expand Down Expand Up @@ -72,20 +73,6 @@ const OP_CHECKMULTISIGVERIFY = 0xaf;
const ANNEX_TAG = 0x50;
const MAX_SATOSHIS = 0xffff_ffff_ffff_ffffn;

/**
* Reads hex the caller passed.
* @param value - Hex without 0x
* @param name - What the error calls it
* @returns {Uint8Array} The bytes
* @throws {TypeError} When the value is no even-length hex
*/
function decodeHex(value: unknown, name: string): Uint8Array {
if (typeof value !== "string" || !/^(?:[0-9a-f]{2})*$/iu.test(value)) {
throw new TypeError(`${name} must be hex without 0x`);
}
return Uint8Array.fromHex(value);
}

/**
* Reads a spent output the caller passed.
* @param output - Script hex and value in satoshis
Expand All @@ -103,21 +90,6 @@ function readSpentOutput(output: Readonly<SpentOutput>, position: number): Trans
return { script, value: amount };
}

/**
* Decodes the raw transaction, naming the encoding rule it breaks.
* @param transaction - Raw transaction hex
* @returns {Transaction} The transaction
* @throws {RangeError} When the bytes are no transaction
*/
function readTransaction(transaction: string): Transaction {
const bytes = decodeHex(transaction, "Transaction");
try {
return decodeTransaction(bytes);
} catch (error) {
throw new RangeError(`Transaction ${error instanceof Error ? error.message : "is unreadable"}`);
}
}

/**
* Reads the transaction and picks the input and the output it spends.
* @param transaction - Raw transaction hex
Expand All @@ -127,7 +99,7 @@ function readTransaction(transaction: string): Transaction {
*/
function readSpend(transaction: string, options: SignatureExtractionOptions): Spend {
const { index, spent } = options;
const decoded = readTransaction(transaction);
const decoded = decode(transaction);
const input = Number.isSafeInteger(index) ? decoded.inputs[index] : undefined;
if (input === undefined) {
throw new RangeError(
Expand Down
30 changes: 30 additions & 0 deletions src/utils/transaction/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,36 @@ export function decodeTransaction(bytes: Uint8Array): Transaction {
return { version, inputs: witnessed, outputs, lockTime };
}

/**
* Reads hex the caller passed.
* @param value - Hex without 0x
* @param name - What the error calls it
* @returns {Uint8Array} The bytes
* @throws {TypeError} When the value is no even-length hex
*/
export function decodeHex(value: unknown, name: string): Uint8Array {
if (typeof value !== "string" || !/^(?:[0-9a-f]{2})*$/iu.test(value)) {
throw new TypeError(`${name} must be hex without 0x`);
}
return Uint8Array.fromHex(value);
}

/**
* Reads a raw Bitcoin transaction, outputs in wire order with their exact satoshis.
* @param transaction - Raw transaction hex, with or without witnesses
* @returns {Transaction} The transaction, each `txid` in hash order, not explorer order
* @throws {TypeError} When the transaction is no even-length hex
* @throws {RangeError} When the bytes are no transaction, naming the encoding rule they break
*/
export function decode(transaction: string): Transaction {
const bytes = decodeHex(transaction, "Transaction");
try {
return decodeTransaction(bytes);
} catch (error) {
throw new RangeError(`Transaction ${error instanceof Error ? error.message : "is unreadable"}`);
}
}

/**
* Reads a serialized witness stack, the body of a BIP322 simple signature.
* @param bytes - The stack bytes
Expand Down
10 changes: 9 additions & 1 deletion test/public-exports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,11 +278,18 @@ describe("Public transaction exports", () => {
if (a === undefined || b === undefined) throw new Error("missing signature");
expect(recoverReusedNonce([a, b]).publicKey).toMatch(/^0[23]dbd0c615/u);
expect(new Set(Object.keys(transaction))).toEqual(
new Set(["extractSignatures", "recoverSigner"]),
new Set(["decode", "extractSignatures", "recoverSigner"]),
);
expect(await import("@agntn/keys")).not.toHaveProperty("extractSignatures");
});

it("reads the outputs of a SegWit transaction from the built package", async () => {
const { decode } = await import("@agntn/keys/transaction");
const [first] = decode(transactionVectors.p2wpkh.transaction).outputs;
expect(first?.value).toBe(112_340_000n);
expect(await import("@agntn/keys")).not.toHaveProperty("decode");
});

it("recovers an EVM transaction signer from the built package", async () => {
const { recoverSigner } = await import("@agntn/keys/transaction");
const { type2 } = evmTransactionVectors;
Expand Down Expand Up @@ -594,6 +601,7 @@ describe("Consumer bundles", () => {
["decrypt", "@agntn/keys/bip38"],
["deriveWif", "@agntn/keys/bip85"],
["verify", "@agntn/keys/bip322"],
["decode", "@agntn/keys/transaction"],
["extractSignatures", "@agntn/keys/transaction"],
["recoverSigner", "@agntn/keys/transaction"],
["multisig", "@agntn/keys/script"],
Expand Down
31 changes: 30 additions & 1 deletion test/utils/transaction.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { hex } from "@agntn/encodings/hex";
import { secp256k1 } from "@noble/curves/secp256k1.js";
import { describe, expect, it } from "vite-plus/test";
import { extractSignatures } from "../../src/utils/transaction/index.ts";
import { decode, extractSignatures } from "../../src/utils/transaction/index.ts";
import { pushOf, scriptPushes } from "../../src/utils/transaction/script.ts";
import { legacySighash, taprootSighash } from "../../src/utils/transaction/sighash.ts";
import {
Expand Down Expand Up @@ -90,6 +90,35 @@ const withScriptSig = (scriptSig: string): string => {
return hex.encode(serializeTransaction({ ...unsigned2012, inputs }, false));
};

describe("decode", () => {
it("reads the one output of the 2012 transaction, the P2PKH both inputs spend", () => {
const { outputs, inputs, lockTime } = decode(reusedNonce2012.transaction);
expect(inputs).toHaveLength(2);
expect(lockTime).toBe(0);
expect(outputs.map(({ value, script }) => [value, hex.encode(script)])).toEqual([
[100_000n, reusedNonce2012.spent[0].script],
]);
});

it("reads the outputs of the signed BIP143 P2WPKH example, witnesses and all", () => {
const { outputs, inputs, lockTime } = decode(p2wpkh.transaction);
expect(outputs.map(({ value, script }) => [value, hex.encode(script)])).toEqual([
[112_340_000n, "76a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac"],
[223_450_000n, "76a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac"],
]);
expect(inputs[1]?.witness.map((item) => hex.encode(item))[1]).toBe(p2wpkh.publicKey);
expect(lockTime).toBe(17);
});

it("names what is wrong with input that is no transaction", () => {
expect(() => decode("0x00")).toThrow(TypeError);
expect(() => decode("0100")).toThrow("Transaction ends early");
expect(() => decode(`${reusedNonce2012.transaction}00`)).toThrow(
"Transaction has bytes past its end",
);
});
});

describe("pushOf", () => {
it("pushes directly up to 75 bytes, then with the shortest OP_PUSHDATA", () => {
const heads = [75, 76, 255, 256].map((length) =>
Expand Down
Loading
0