Skip to content
Open
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
3 changes: 1 addition & 2 deletions packages/cashscript/src/libauth-template/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,12 @@ import {
ResolvedTransactionCommon,
createVirtualMachineBch2023,
createVirtualMachineBch2025,
createVirtualMachineBch2026,
createVirtualMachineBchSpec,
} from '@bitauth/libauth';
import { EncodedFunctionArgument } from '../Argument.js';
import { zip } from '../utils.js';
import SignatureTemplate from '../SignatureTemplate.js';
import { Contract } from '../Contract.js';
import { createVirtualMachineBch2026, createVirtualMachineBchSpec } from './virtual-machine.js';

export const DEFAULT_VM_TARGET = VmTarget.BCH_2026_05;

Expand Down
60 changes: 60 additions & 0 deletions packages/cashscript/src/libauth-template/virtual-machine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import {
AuthenticationProgramBch,
AuthenticationProgramStateBch2026,
AuthenticationProgramStateBchSpec,
AuthenticationVirtualMachineBch2026,
AuthenticationVirtualMachineBchSpec,
InstructionSet,
OpcodesBch,
Operation,
ResolvedTransactionBch,
createInstructionSetBch2026,
createInstructionSetBchSpec,
createVirtualMachine,
} from '@bitauth/libauth';

// Drop-in replacements for libauth's createVirtualMachineBch2026 and createVirtualMachineBchSpec, as a workaround for
// https://github.com/bitauth/libauth/issues/166: libauth's OP_DEFINE does not add the length of the function body to the
// operation cost, while BCHN does (as specified by the Functions CHIP). Without this, local evaluation under-reports the
// operation cost of any contract that defines functions, and accepts transactions that the network rejects for exceeding
// the operation cost budget.
export const createVirtualMachineBch2026 = (): AuthenticationVirtualMachineBch2026 => createVirtualMachine(
chargeFunctionBodyOnDefine(createInstructionSetBch2026<AuthenticationProgramStateBch2026>()),
);

export const createVirtualMachineBchSpec = (): AuthenticationVirtualMachineBchSpec => createVirtualMachine(
chargeFunctionBodyOnDefine(createInstructionSetBchSpec<AuthenticationProgramStateBchSpec>()),
);

type InstructionSetBch<State> = InstructionSet<ResolvedTransactionBch, AuthenticationProgramBch, State>;

export function chargeFunctionBodyOnDefine<State extends AuthenticationProgramStateBch2026>(
instructionSet: InstructionSetBch<State>,
): InstructionSetBch<State> {
return {
...instructionSet,
operations: {
...instructionSet.operations,
[OpcodesBch.OP_DEFINE]: chargeFunctionBody(instructionSet.operations[OpcodesBch.OP_DEFINE]!),
},
};
}

// Only the part of the function body that the wrapped OP_DEFINE did not charge itself is added, so the operation cost
// stays correct (instead of being counted twice) when this runs on a libauth version that includes the fix.
function chargeFunctionBody<State extends AuthenticationProgramStateBch2026>(define: Operation<State>): Operation<State> {
return (state) => {
// OP_DEFINE pops <function body> <function identifier>, so these have to be read before it runs
const functionBodyLength = state.stack.at(-2)?.length ?? 0;
const { functionCount } = state;
const { stackPushedBytes } = state.metrics;

const nextState = define(state);

const isDefined = nextState.functionCount > functionCount;
const chargedBytes = nextState.metrics.stackPushedBytes - stackPushedBytes;
if (isDefined) nextState.metrics.stackPushedBytes += Math.max(functionBodyLength - chargedBytes, 0);

return nextState;
};
}
70 changes: 69 additions & 1 deletion packages/cashscript/test/debugging.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ import { Contract, FailedTransactionEvaluationError, MockNetworkProvider, Signat
import { DEFAULT_VM_TARGET, getLockScriptName } from '../src/libauth-template/utils.js';
import { aliceAddress, alicePriv, alicePub, bobPriv, bobPub } from './fixture/vars.js';
import { randomUtxo } from '../src/utils.js';
import { AuthenticationErrorBch2025Additions, AuthenticationErrorCommon, binToHex, hexToBin } from '@bitauth/libauth';
import { AuthenticationErrorBch2025Additions, AuthenticationErrorCommon, binToHex, hexToBin, OpcodesBch } from '@bitauth/libauth';
import {
artifactTestMultipleConstructorParameters,
artifactTestLogs,
artifactTestOperationCostOverrun,
artifactTestDefineOperationCost,
artifactTestConsecutiveLogs,
artifactTestMultipleLogs,
artifactTestRequires,
Expand Down Expand Up @@ -850,6 +851,15 @@ describe('Debugging tests', () => {
});
});

// The operation cost of the first OP_DEFINE that input 0 executes: the base instruction cost plus the function body length
const measureDefineOperationCost = (transaction: TransactionBuilder): number => {
const [debugSteps] = Object.values(transaction.debug());
const defineIndex = debugSteps.findIndex((step) => step.instructions[step.ip]?.opcode === OpcodesBch.OP_DEFINE);
expect(defineIndex).toBeGreaterThan(-1);

return debugSteps[defineIndex + 1].metrics.operationCost - debugSteps[defineIndex].metrics.operationCost;
};

describe('VM Resources', () => {
it('Should output VM resource usage', async () => {
const provider = new MockNetworkProvider();
Expand Down Expand Up @@ -883,6 +893,64 @@ describe('VM Resources', () => {
expect(vmUsage[0]?.hashDigestIterations).toBeGreaterThan(0);
expect(vmUsage[2]?.hashDigestIterations).toBeGreaterThan(0);
});

// libauth does not charge the function body on OP_DEFINE (https://github.com/bitauth/libauth/issues/166), the SDK does
it('should include the function body length in the operation cost of OP_DEFINE', () => {
const provider = new MockNetworkProvider();
const contract = new Contract(artifactTestFunctionDebuggingDefined, [], { provider });
const utxo = provider.addUtxo(contract.address, randomUtxo());
const [definedFunction] = artifactTestFunctionDebuggingDefined.debug!.functions!;

const transaction = new TransactionBuilder({ provider })
.addInput(utxo, contract.unlock.spend(5n))
.addOutput({ to: contract.address, amount: 10000n });

expect(measureDefineOperationCost(transaction)).toEqual(100 + hexToBin(definedFunction.bytecode).length);
});

it('should reject a transaction that only fits the operation cost budget when function bodies are not charged', async () => {
const provider = new MockNetworkProvider();
const contract = new Contract(artifactTestDefineOperationCost, [], { provider });
const [definedFunction] = artifactTestDefineOperationCost.debug!.functions!;
const functionBodyLength = hexToBin(definedFunction.bytecode).length;

// 75 rounds go slightly over the budget of an input without padding, which keeps the scan below short
const buildTransaction = (padding: number): TransactionBuilder => new TransactionBuilder({ provider })
.addInput(
provider.addUtxo(contract.address, randomUtxo()),
contract.unlock.spend(new Uint8Array(1), 75n, new Uint8Array(padding)),
)
.addOutput({ to: aliceAddress, amount: 1000n });

const fitsBudget = (padding: number): boolean => {
try {
buildTransaction(padding).debug();
return true;
} catch (error) {
expect(error).toBeInstanceOf(FailedTransactionEvaluationError);
expect((error as FailedTransactionEvaluationError).libauthErrorMessage)
.toContain(AuthenticationErrorBch2025Additions.excessiveOperationCost);
return false;
}
};

let padding = 0;
while (padding < 75 && !fitsBudget(padding)) padding++;
expect(padding).toBeGreaterThan(0);
expect(padding).toBeLessThan(75);

// With one byte of padding less, the budget is 800 lower and one byte less is pushed. That is rejected (in the scan
// above), but it would fit if the function body were not charged, so the function body decides the outcome
const [usage] = buildTransaction(padding).getVmResourceUsage();
expect(measureDefineOperationCost(buildTransaction(padding))).toEqual(100 + functionBodyLength);
expect(usage.operationCost - 1).toBeGreaterThan(usage.maximumOperationCost - 800);
expect(usage.operationCost - 1 - functionBodyLength).toBeLessThanOrEqual(usage.maximumOperationCost - 800);

// The MockNetworkProvider validates transactions by itself, and draws the same line
await expect(provider.sendRawTransaction(buildTransaction(padding).build())).resolves.toBeDefined();
await expect(provider.sendRawTransaction(buildTransaction(padding - 1).build()))
.rejects.toThrow(AuthenticationErrorBch2025Additions.excessiveOperationCost);
});
});

describe('Debugging tests - user-defined function frames', () => {
Expand Down
23 changes: 23 additions & 0 deletions packages/cashscript/test/fixture/debugging/debugging_contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,25 @@ contract Test() {
}
`;

// The loop spends most of the operation cost budget, and the padding sets how much budget the input gets, so a test can
// find the smallest padding that fits. The function body is longer than the budget that one byte of padding adds (800),
// so with one byte less the transaction only fits if the function body is not charged on OP_DEFINE
const CONTRACT_TEST_DEFINE_OPERATION_COST = `
function checkData(bytes data) {
require(data != 0x${'ab'.repeat(1000)}, "data must differ");
}

contract Test() {
function spend(bytes data, int rounds, bytes unused padding) {
checkData(data);
for (int i = 0; i < rounds; i = i + 1) {
require(toPaddedBytes(i, 10000).length == 10000, "padded bytes must be 10000 bytes long");
}
require(tx.outputs[0].value >= 1000, "Output 0 must keep 1000 sats");
}
}
`;

export const artifactTestRequires = compileString(CONTRACT_TEST_REQUIRES);
export const artifactTestSingleFunction = compileString(CONTRACT_TEST_REQUIRE_SINGLE_FUNCTION);
export const artifactTestMultilineRequires = compileString(CONTRACT_TEST_MULTILINE_REQUIRES);
Expand Down Expand Up @@ -642,6 +661,10 @@ export const artifactTestNestedImportedFunctions = compileString(
export const artifactTestMixedNestedFunctions = compileString(CONTRACT_TEST_MIXED_NESTED_FUNCTIONS);
export const artifactTestInlinedCallingDefined = compileString(CONTRACT_TEST_INLINED_CALLING_DEFINED);
export const artifactTestOperationCostOverrun = compileString(CONTRACT_TEST_OPERATION_COST_OVERRUN);
export const artifactTestDefineOperationCost = compileString(
CONTRACT_TEST_DEFINE_OPERATION_COST,
{ disableInlining: true },
);

// Compiled from a file so the imported function (function_helpers.cash) keeps its own source provenance.
export const artifactTestImportedFunctionDebugging = compileFile(new URL('./function_importer.cash', import.meta.url));
Expand Down
105 changes: 105 additions & 0 deletions packages/cashscript/test/libauth-template/virtual-machine.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import {
AuthenticationProgramCommon,
AuthenticationProgramStateBch2026,
createInstructionSetBch2026,
createVirtualMachine as createLibauthVirtualMachine,
createVirtualMachineBch2026,
createVirtualMachineBchSpec,
encodeDataPush,
flattenBinArray,
OpcodesBch,
} from '@bitauth/libauth';
import { VmTarget } from '../../src/index.js';
import { createVirtualMachine, VM } from '../../src/libauth-template/utils.js';
import { chargeFunctionBodyOnDefine } from '../../src/libauth-template/virtual-machine.js';

const BASE_INSTRUCTION_COST = 100;
const FUNCTION_BODY = new Uint8Array(1000).fill(OpcodesBch.OP_NOP);

// <function body> <0> OP_DEFINE <1>
const DEFINE_SCRIPT = flattenBinArray([
encodeDataPush(FUNCTION_BODY),
Uint8Array.of(OpcodesBch.OP_0, OpcodesBch.OP_DEFINE, OpcodesBch.OP_1),
]);

// 4 instructions, and pushed bytes for the function body push, its definition and the final <1>
const DEFINE_SCRIPT_OPERATION_COST = 4 * BASE_INSTRUCTION_COST + FUNCTION_BODY.length + FUNCTION_BODY.length + 1;

// <function body> <0> <0> OP_IF OP_DEFINE OP_ENDIF OP_2DROP <1>
// The skipped OP_DEFINE has a function body and identifier on the stack, like one that is executed
const SKIPPED_DEFINE_SCRIPT = flattenBinArray([
encodeDataPush(FUNCTION_BODY),
Uint8Array.of(OpcodesBch.OP_0, OpcodesBch.OP_0, OpcodesBch.OP_IF, OpcodesBch.OP_DEFINE, OpcodesBch.OP_ENDIF),
Uint8Array.of(OpcodesBch.OP_2DROP, OpcodesBch.OP_1),
]);

const createProgram = (lockingBytecode: Uint8Array): AuthenticationProgramCommon => ({
inputIndex: 0,
sourceOutputs: [{ lockingBytecode, valueSatoshis: 1000n }],
transaction: {
version: 2,
locktime: 0,
inputs: [{
outpointIndex: 0,
outpointTransactionHash: new Uint8Array(32),
sequenceNumber: 0,
unlockingBytecode: new Uint8Array(),
}],
outputs: [{ lockingBytecode: Uint8Array.of(OpcodesBch.OP_RETURN), valueSatoshis: 0n }],
},
});

const measureOperationCost = (vm: VM, lockingBytecode: Uint8Array): number => {
const state = vm.evaluate(createProgram(lockingBytecode));
expect(state.error).toBeUndefined();
return state.metrics.operationCost;
};

const STOCK_VIRTUAL_MACHINES: Array<[VmTarget, VM]> = [
[VmTarget.BCH_2026_05, createVirtualMachineBch2026()],
[VmTarget.BCH_SPEC, createVirtualMachineBchSpec() as unknown as VM],
];

// Workaround for https://github.com/bitauth/libauth/issues/166
describe('createVirtualMachine', () => {
describe.each(STOCK_VIRTUAL_MACHINES)('OP_DEFINE operation cost (%s)', (vmTarget, stockVm) => {
it('should charge the function body length when a function is defined', () => {
expect(measureOperationCost(createVirtualMachine(vmTarget), DEFINE_SCRIPT)).toEqual(DEFINE_SCRIPT_OPERATION_COST);
});

it('should not charge the function body length for an OP_DEFINE in a branch that is not executed', () => {
const operationCost = measureOperationCost(createVirtualMachine(vmTarget), SKIPPED_DEFINE_SCRIPT);

expect(operationCost).toEqual(measureOperationCost(stockVm, SKIPPED_DEFINE_SCRIPT));
});
});

it('should not charge the function body length twice when libauth already charges it', () => {
// Stands in for a libauth version that includes the fix
const instructionSet = createInstructionSetBch2026<AuthenticationProgramStateBch2026>();
const define = instructionSet.operations[OpcodesBch.OP_DEFINE]!;
const fixedInstructionSet = {
...instructionSet,
operations: {
...instructionSet.operations,
[OpcodesBch.OP_DEFINE]: (state: AuthenticationProgramStateBch2026): AuthenticationProgramStateBch2026 => {
const functionBody = state.stack.at(-2)!;
const nextState = define(state);
nextState.metrics.stackPushedBytes += functionBody.length;
return nextState;
},
},
};
const wrappedFixedVm = createLibauthVirtualMachine(chargeFunctionBodyOnDefine(fixedInstructionSet));

expect(measureOperationCost(wrappedFixedVm, DEFINE_SCRIPT)).toEqual(DEFINE_SCRIPT_OPERATION_COST);
});

// Not a requirement of the SDK: this fails once libauth charges the function body itself. The workaround stays
// correct when that happens, but it can then be removed together with this test.
it('is still needed, because stock libauth does not charge the function body length', () => {
const stockOperationCost = measureOperationCost(createVirtualMachineBch2026(), DEFINE_SCRIPT);

expect(stockOperationCost).toEqual(DEFINE_SCRIPT_OPERATION_COST - FUNCTION_BODY.length);
});
});
Loading