Merge pull request #579 from LedgerHQ/misc-fixes
What changed, and why it matters
This commit fixes several bugs in Ledger's Bitcoin app. The most serious ones are: (1) a set of miniscript policy analyzer mistakes that could let the app accept Bitcoin wallet policies whose scripts are too large or too expensive to execute safely, and (2) a denial-of-service issue where a malicious computer app could keep the Ledger stuck in a slow loop forever by sending empty data chunks. It also fixes a UI glitch where a warning screen could be accidentally cleared by the next command.
Treat this as a security-relevant fix release. Users should upgrade the Bitcoin app once Ledger publishes it. Developers relying on miniscript policy registration should re-validate registered policies after upgrading, and review any custom client code to ensure it does not rely on the previously buggy analyzer behavior.
Security signals we found
Miniscript cost/property analysis errors that could allow oversized/undercosted wallet policies
Host-driven infinite-loop / denial-of-service via zero-length GET_MORE_ELEMENTS responses
UI state inconsistency causing a security warning to be prematurely dismissed
New adversarial unit tests and Python regression tests added for the above
No CVE, vendor security advisory, or researcher attribution present in commit materials
Evidence from the diff
The patch corrects multiple flaws in compute_miniscript_policy_ext_info() in src/common/wallet.c: wrong dissatisfaction operands used for or_d and andor cost calculations, incorrect ‘e’ and ‘m’ property propagation for andor/and_n/a: wrappers, and a timelock-mixing self-comparison bug in thresh. These errors could undercount Bitcoin script op-costs/stack sizes and wrongly mark policies as sane/non-malleable. The patch also hardens get_merkle_leaf_hash, get_merkle_preimage, get_preimage and stream_preimage to reject zero-length continuation responses, preventing a host from keeping a command alive without progress. A UI state fix in ui_warn_nondefault_sighash_disabled() marks the screen dirty and clears the spinner flag so the warning is not dismissed by a later command.
Changed components
src/common/wallet.c (miniscript policy analyzer)src/handler/lib/get_merkle_leaf_hash.csrc/handler/lib/get_merkle_preimage.csrc/handler/lib/get_preimage.csrc/handler/lib/stream_preimage.csrc/ui/display.cInspect captured patch +413 / −31
### src/common/wallet.c
@@ -2158,8 +2158,8 @@ static int16_t maxcheck(int16_t a, int16_t b) {
__attribute__((noinline)) static int compute_thresh_ops(const policy_node_thresh_t *node,
miniscript_ops_t *out,
MiniscriptContext ctx) {
- uint16_t sats[MAX_N_IN_THRESH + 1 + 1] = {0};
- uint16_t next_sats[MAX_N_IN_THRESH + 1 + 1] = {0}; // it temporarily uses an extra element
+ int16_t sats[MAX_N_IN_THRESH + 1 + 1] = {0};
+ int16_t next_sats[MAX_N_IN_THRESH + 1 + 1] = {0}; // it temporarily uses an extra element
if (node->n > MAX_N_IN_THRESH) return -1;
@@ -2197,8 +2197,8 @@ __attribute__((noinline)) static int compute_thresh_ops(const policy_node_thresh
__attribute__((noinline)) static int compute_thresh_stacksize(const policy_node_thresh_t *node,
miniscript_stacksize_t *out,
MiniscriptContext ctx) {
- uint16_t sats[MAX_N_IN_THRESH + 1 + 1] = {0};
- uint16_t next_sats[MAX_N_IN_THRESH + 1 + 1] = {0}; // it temporarily uses an extra element
+ int16_t sats[MAX_N_IN_THRESH + 1 + 1] = {0};
+ int16_t next_sats[MAX_N_IN_THRESH + 1 + 1] = {0}; // it temporarily uses an extra element
if (node->n > MAX_N_IN_THRESH) return -1;
@@ -2427,7 +2427,7 @@ int compute_miniscript_policy_ext_info(const policy_node_t *policy_node,
out->ops = (miniscript_ops_t) {
3 + x.ops.count + y.ops.count + z.ops.count,
- maxcheck(sumcheck(y.ops.sat, x.ops.sat), sumcheck(y.ops.dsat, z.ops.sat)),
+ maxcheck(sumcheck(y.ops.sat, x.ops.sat), sumcheck(x.ops.dsat, z.ops.sat)),
sumcheck(x.ops.dsat, z.ops.dsat)};
out->ss = (miniscript_stacksize_t) {
maxcheck(sumcheck(x.ss.sat, y.ss.sat), sumcheck(x.ss.dsat, z.ss.sat)),
@@ -2513,7 +2513,8 @@ int compute_miniscript_policy_ext_info(const policy_node_t *policy_node,
out->s = x.s | y.s;
out->e = x.s | y.f;
- out->m = x.m & y.m & x.e & (x.s | y.s);
+ // andor(X,Y,0) requires s_X + s_Y + s_0, but s_0 = 1
+ out->m = x.m & y.m & x.e;
out->g = x.g | y.g;
out->h = x.h | y.h;
@@ -2527,7 +2528,7 @@ int compute_miniscript_policy_ext_info(const policy_node_t *policy_node,
out->script_size = 4 + x.script_size + y.script_size;
out->ops = (miniscript_ops_t) {3 + x.ops.count + y.ops.count,
- maxcheck(sumcheck(y.ops.sat, x.ops.sat), y.ops.dsat),
+ sumcheck(x.ops.sat, y.ops.sat),
x.ops.dsat};
out->ss = (miniscript_stacksize_t) {sumcheck(x.ss.sat, y.ss.sat), x.ss.dsat};
return 0;
@@ -2542,7 +2543,7 @@ int compute_miniscript_policy_ext_info(const policy_node_t *policy_node,
if (0 > compute_miniscript_policy_ext_info(node->scripts[1], &z, ctx)) return -1;
out->s = x.s & z.s;
- out->e = 1;
+ out->e = x.e & z.e;
out->m = x.m & z.m & x.e & z.e & (x.s | z.s);
@@ -2685,26 +2686,28 @@ int compute_miniscript_policy_ext_info(const policy_node_t *policy_node,
}
cur = cur->next;
- out->g |= t.g;
- out->h |= t.h;
- out->i |= t.i;
- out->j |= t.j;
-
out->k &= t.k; // if any child doesn't have k, thresh doesn't have k
- // if any two children have mixed timelocks, thresh doesn't have k
+ // if any two children have mixed timelocks, thresh doesn't have k.
+ // This must be checked before accumulating the timelocks of the current child,
+ // as a child is not mixing timelocks with itself.
if (node->k >= 2 &&
((t.g & out->h) || (t.h & out->g) || (t.i & out->j) || (t.j & out->i))) {
out->k = 0;
}
+ out->g |= t.g;
+ out->h |= t.h;
+ out->i |= t.i;
+ out->j |= t.j;
+
children_scriptsize += t.script_size;
}
int count_not_s = node->n - count_s;
out->s = count_not_s <= node->k - 1 ? 1 : 0;
- out->e = count_s == node->n ? 1 : 0;
+ out->e = (count_e == node->n && count_s == node->n) ? 1 : 0;
out->m = (count_e == node->n && count_m == node->n && count_not_s <= node->k) ? 1 : 0;
@@ -2806,7 +2809,7 @@ int compute_miniscript_policy_ext_info(const policy_node_t *policy_node,
if (0 > compute_miniscript_policy_ext_info(node->script, &x, ctx)) return -1;
out->s = x.s;
- out->e = 1;
+ out->e = x.f;
out->m = x.m;
@@ -2917,7 +2920,7 @@ int compute_miniscript_policy_ext_info(const policy_node_t *policy_node,
out->script_size = x.script_size + 4;
- out->ops = (miniscript_ops_t) {3 + x.ops.count, x.ops.sat, x.ops.dsat};
+ out->ops = (miniscript_ops_t) {3 + x.ops.count, x.ops.sat, maxcheck(0, x.ops.dsat)};
out->ss = (miniscript_stacksize_t) {sumcheck(x.ss.sat, 1),
maxcheck(1, sumcheck(x.ss.dsat, 1))};
### src/handler/lib/get_merkle_leaf_hash.c
@@ -133,8 +133,8 @@ static int get_merkle_leaf_hash(dispatcher_context_t *dc,
return -1;
}
- if (cur_step + n_proof_elements > proof_size) {
- // Receiving more data then expected
+ if (n_proof_elements == 0 || cur_step + n_proof_elements > proof_size) {
+ // Receiving no data (no progress), or more data than expected
return -1;
}
}
### src/handler/lib/get_merkle_preimage.c
@@ -103,8 +103,9 @@ static int get_merkle_preimage(dispatcher_context_t *dispatcher_context,
return -8;
}
- if (n_bytes > bytes_remaining) {
- PRINTF("Received more bytes than expected.\n");
+ if (n_bytes == 0 || n_bytes > bytes_remaining) {
+ // n_bytes == 0 would not make progress, allowing the host to keep the loop going
+ PRINTF("Received an invalid number of bytes.\n");
return -9;
}
### src/handler/lib/get_preimage.c
@@ -96,8 +96,9 @@ static int get_preimage(dispatcher_context_t *dispatcher_context,
return -7;
}
- if (n_bytes > bytes_remaining) {
- PRINTF("Received more bytes than expected.\n");
+ if (n_bytes == 0 || n_bytes > bytes_remaining) {
+ // n_bytes == 0 would not make progress, allowing the host to keep the loop going
+ PRINTF("Received an invalid number of bytes.\n");
return -8;
}
### src/handler/lib/stream_preimage.c
@@ -99,8 +99,9 @@ int call_stream_preimage(dispatcher_context_t *dispatcher_context,
return -7;
}
- if (n_bytes > bytes_remaining) {
- PRINTF("Received more bytes than expected.\n");
+ if (n_bytes == 0 || n_bytes > bytes_remaining) {
+ // n_bytes == 0 would not make progress, allowing the host to keep the loop going
+ PRINTF("Received an invalid number of bytes.\n");
return -8;
}
### src/ui/display.c
@@ -283,8 +283,10 @@ void ui_warn_nondefault_sighash_disabled(dispatcher_context_t *context) {
return;
#endif
- UNUSED(context);
- // Fire-and-forget terminal status
+ // Fire-and-forget terminal status; set the UI as dirty, since something is shown on screen.
+ // The status replaces the spinner, so later commands must not treat the spinner as shown.
+ G_was_processing_screen_shown = false;
+ context->set_ui_dirty();
ui_display_nondefault_sighash_disabled_flow();
}
### tests/test_register_wallet.py
@@ -497,8 +497,67 @@ def test_register_wallet_not_sane_policy(navigator: Navigator, firmware: Firmwar
assert error_code == EC_REGISTER_WALLET_POLICY_NOT_SANE
- # TODO: we can probably not trigger stack and ops limits with the current limits we have on the
- # miniscript policy size; otherwise it would be worth to add tests for them, too.
+ # Miniscript policy exceeding the 201 ops limit only when satisfying the multi in the second branch
+ # of the or_d. The ops of that branch are only accounted for if the dissatisfaction of the 'u:'
+ # wrapper (via its constant 0 branch) is.
+ keys = ",".join(f"@{i}/**" for i in range(10))
+ with pytest.raises(ExceptionRAPDU) as e:
+ client.register_wallet(WalletPolicy(
+ name="Too many ops",
+ descriptor_template=f"wsh(or_d(utv:or_i(jjjjjjjjjj:pk(@10/**),jjjjjjjjjj:pk(@11/**)),or_i(jjjjjjjjjjjjj:multi(1,{keys}),jjjjjjjjjjjjj:pk(@12/**))))",
+ keys_info=[
+ "[f5acc2fd/48'/1'/0'/2']tpubDFAqEGNyad35aBCKUAXbQGDjdVhNueno5ZZVEn3sQbW5ci457gLR7HyTmHBg93oourBssgUxuWz1jX5uhc1qaqFo9VsybY1J5FuedLfm4dK",
+ "tpubDE7NQymr4AFtewpAsWtnreyq9ghkzQBXpCZjWLFVRAvnbf7vya2eMTvT2fPapNqL8SuVvLQdbUbMfWLVDCZKnsEBqp6UK93QEzL8Ck23AwF",
+ "tpubDDV6FDLcCieWUeN7R3vZK2Qs3KuQed3ScTY9EiwMXvyCkLjDbCb8RXaAgWDbkG4tW1BMKVF1zERHnyt78QKd4ZaAYGMJMpvHPwgSSU1AxZ3",
+ "tpubDF6JT5K4izwALMpFv7fQrpWr5bGUMEoWphkzTVJH8jTfgirNE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5usanzups5rj7PJoQLNyvq8QbJruW",
+ ]),
+ navigator,
+ testname=test_name
+ )
+ assert DeviceException.exc.get(e.value.status) == NotSupportedError
+ assert len(e.value.data) == 2
+ error_code = int.from_bytes(e.value.data, 'big')
+ assert error_code == EC_REGISTER_WALLET_POLICY_NOT_SANE
+
+ # Miniscript policy exceeding the 201 ops limit only when satisfying the multi in the Z branch
+ # of the andor. The ops of that branch are only accounted for if the dissatisfaction of X (rather
+ # than of Y, which can't be dissatisfied) is used for that satisfaction path.
+ with pytest.raises(ExceptionRAPDU) as e:
+ client.register_wallet(WalletPolicy(
+ name="Too many ops",
+ descriptor_template=f"wsh(t:andor(pk(@10/**),v:or_i(jjjjjjjjjjj:pk(@11/**),jjjjjjjjjjj:pk(@12/**)),v:or_i(jjjjjjjjjjj:multi(1,{keys}),jjjjjjjjjjj:pk(@13/**))))",
+ keys_info=[
+ "[f5acc2fd/48'/1'/0'/2']tpubDFAqEGNyad35aBCKUAXbQGDjdVhNueno5ZZVEn3sQbW5ci457gLR7HyTmHBg93oourBssgUxuWz1jX5uhc1qaqFo9VsybY1J5FuedLfm4dK",
+ "tpubDE7NQymr4AFtewpAsWtnreyq9ghkzQBXpCZjWLFVRAvnbf7vya2eMTvT2fPapNqL8SuVvLQdbUbMfWLVDCZKnsEBqp6UK93QEzL8Ck23AwF",
+ "tpubDDV6FDLcCieWUeN7R3vZK2Qs3KuQed3ScTY9EiwMXvyCkLjDbCb8RXaAgWDbkG4tW1BMKVF1zERHnyt78QKd4ZaAYGMJMpvHPwgSSU1AxZ3",
+ "tpubDF6JT5K4izwALMpFv7fQrpWr5bGUMEoWphkzTVJH8jTfgirNEgGZnxsWJDCCxhg2UnW5RcD9Tx8aVAdoM734X5bnRGmJUujz26uQ5gAC1nE",
+ "tpubDF4kujkh5dAhC1pFgBToZybXdvJFXXGX4BWdDxWqP7EUpG8gxkfMQeDjGPDnTr9e4NrkFmDM1ocav3Jz6x79CRZbxGr9dzFokJLuvDDnyRh",
+ "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DeviceException.exc.get(e.value.status) == NotSupportedError
+ assert len(e.value.data) == 2
+ error_code = int.from_bytes(e.value.data, 'big')
+ assert error_code == EC_REGISTER_WALLET_POLICY_NOT_SANE
def test_register_unusual_singlesig_accounts(navigator: Navigator, firmware: Firmware, client:
### tests/test_sighash_setting.py
@@ -13,10 +13,12 @@
import pytest
from pathlib import Path
from ledger_bitcoin import WalletPolicy
+from ledger_bitcoin.client_command import ClientCommandInterpreter
from ledger_bitcoin.exception.errors import NotSupportedError, SecurityStatusNotSatisfiedError
from ledger_bitcoin.exception.device_exception import DeviceException
from ledger_bitcoin.psbt import PSBT
from test_utils import bip0340
+from ragger.backend import BackendInterface
from ragger.navigator import Navigator, NavInsID, NavIns
from ragger.error import ExceptionRAPDU
from ragger.firmware import Firmware
@@ -105,6 +107,47 @@ def test_sighash_none_rejected_by_default(navigator: Navigator, firmware: Firmwa
assert_disabled_sighash_screen(navigator, default_screenshot_path, test_name)
+def test_sighash_rejected_status_not_dismissed_by_next_command(
+ backend: BackendInterface, client: RaggerClient, monkeypatch: pytest.MonkeyPatch):
+ """Regression test: if the "Processing..." spinner was shown before the rejection, the
+ rejection status replaces it. A subsequent command that has no UI of its own must not
+ dismiss the status by returning to the dashboard, as it would if the app still believed
+ that the spinner was on screen.
+ """
+ psbt = open_psbt_from_file(f"{tests_root}/psbt/sighash/sighash-none-sign.psbt")
+
+ # Hold the first client command response until the spinner is shown (the app shows it
+ # after the command has been running for about 1s), so that the rejection happens after it
+ original_execute = ClientCommandInterpreter.execute
+ spinner_shown = False
+
+ def execute_after_spinner(self, hw_response: bytes) -> bytes:
+ nonlocal spinner_shown
+ if not spinner_shown:
+ backend.wait_for_text_on_screen("Loading")
+ spinner_shown = True
+ return original_execute(self, hw_response)
+
+ monkeypatch.setattr(ClientCommandInterpreter, "execute", execute_after_spinner)
+
+ with pytest.raises(ExceptionRAPDU) as e:
+ client.sign_psbt(psbt, tr_wallet, None)
+ assert spinner_shown
+ assert e.value.status == SW_SECURITY_STATUS_NOT_SATISFIED
+ assert int.from_bytes(e.value.data, 'big') == EC_SIGN_PSBT_NONDEFAULT_SIGHASH_NOT_ALLOWED
+
+ # wait for the rejection screen to appear, since non-standard sighash is disabled
+ backend.wait_for_text_on_screen(".*disabled")
+
+ # Pause the ticker so that the status cannot time out while we check it is still on screen
+ backend.pause_ticker()
+ try:
+ client.get_master_fingerprint()
+ assert backend.compare_screen_with_text(".*disabled")
+ finally:
+ backend.resume_ticker()
+
+
def test_sighash_single_rejected_by_default(navigator: Navigator, firmware: Firmware,
client: RaggerClient, test_name: str):
"""SIGHASH_SINGLE should be rejected when the non-standard sighash setting is disabled (default)."""
### unit-tests/test_get_merkle_leaf_hash.c
@@ -956,6 +956,71 @@ static void test_get_leaf_hash_out_of_range_index(void **state) {
assert_true(call_get_merkle_leaf_hash(dc, root, 0, 0, out) < 0);
}
+/**
+ * Adversarial: every GET_MORE_ELEMENTS response carries zero elements, so it makes no progress.
+ * This must be rejected immediately, otherwise the host could keep the command alive forever.
+ * The response is forged, as the honest handler would fail once its queue is drained; from the
+ * second request on, the hook simulates a communication failure, so that a regression makes the
+ * test fail rather than hang.
+ */
+typedef struct {
+ uint8_t elements_len;
+ int n_empty_responses;
+} empty_more_elements_t;
+
+static int forge_empty_more_elements(const uint8_t *request_buf,
+ size_t request_len,
+ uint8_t *response_buf,
+ size_t *response_len,
+ void *user_data) {
+ (void) request_len;
+ empty_more_elements_t *s = user_data;
+
+ if (request_buf[0] != CCMD_GET_MORE_ELEMENTS) {
+ return 0; /* anything else is answered honestly */
+ }
+
+ if (++s->n_empty_responses > 1) {
+ return -1;
+ }
+
+ response_buf[0] = 0; /* n_elements */
+ response_buf[1] = s->elements_len;
+ *response_len = 2;
+ return 1;
+}
+
+static void test_get_leaf_hash_empty_more_elements(void **state) {
+ mock_dispatcher_t *mock = *state;
+
+ /* depth 7: 6 proof elements fit in the first response, 1 needs GET_MORE_ELEMENTS */
+ uint8_t data[128][2];
+ const uint8_t *elems[128];
+ size_t lens[128];
+ for (size_t i = 0; i < 128; i++) {
+ data[i][0] = (uint8_t) (i >> 8);
+ data[i][1] = (uint8_t) (i & 0xFF);
+ elems[i] = data[i];
+ lens[i] = 2;
+ }
+
+ uint8_t root[32];
+ build_tree(mock, elems, lens, 128, root);
+
+ empty_more_elements_t forge_state = {.elements_len = 32, .n_empty_responses = 0};
+ mock_dispatcher_set_forge_hook(mock, forge_empty_more_elements, &forge_state);
+
+ uint8_t out[32];
+ memset(out, 0xEE, sizeof(out));
+ dispatcher_context_t *dc = mock_dispatcher_get_dc(mock);
+ int result = call_get_merkle_leaf_hash(dc, root, 128, 0, out);
+
+ /* every error is -1 here, so only the response count tells the rejection from the comm failure */
+ assert_int_equal(result, -1);
+ assert_int_equal(forge_state.n_empty_responses, 1);
+ assert_cleared(out, sizeof(out));
+}
+
/* ---------- Main ---------- */
int main(void) {
@@ -978,6 +1043,7 @@ int main(void) {
T(test_get_leaf_hash_more_comm_failure),
T(test_get_leaf_hash_truncated_more),
T(test_get_leaf_hash_more_proof_overflow),
+ T(test_get_leaf_hash_empty_more_elements),
T(test_get_leaf_hash_internal_node_as_leaf),
T(test_get_leaf_hash_proof_size_equals_depth),
T(test_get_leaf_hash_overlong_proof),
### unit-tests/test_get_merkle_preimage.c
@@ -686,6 +686,65 @@ static void test_get_merkle_preimage_bad_prefix(void **state) {
assert_cleared(out, sizeof(out));
}
+/**
+ * Adversarial: every GET_MORE_ELEMENTS response carries zero elements, so it makes no progress.
+ * This must be rejected immediately, otherwise the host could keep the command alive forever.
+ * The response is forged, as the honest handler would fail once its queue is drained; from the
+ * second request on, the hook simulates a communication failure, so that a regression makes the
+ * test fail rather than hang.
+ */
+typedef struct {
+ uint8_t elements_len;
+ int n_empty_responses;
+} empty_more_elements_t;
+
+static int forge_empty_more_elements(const uint8_t *request_buf,
+ size_t request_len,
+ uint8_t *response_buf,
+ size_t *response_len,
+ void *user_data) {
+ (void) request_len;
+ empty_more_elements_t *s = user_data;
+
+ if (request_buf[0] != CCMD_GET_MORE_ELEMENTS) {
+ return 0; /* anything else is answered honestly */
+ }
+
+ if (++s->n_empty_responses > 1) {
+ return -1;
+ }
+
+ response_buf[0] = 0; /* n_elements */
+ response_buf[1] = s->elements_len;
+ *response_len = 2;
+ return 1;
+}
+
+static void test_get_merkle_preimage_empty_more_elements(void **state) {
+ mock_dispatcher_t *mock = *state;
+
+ /* element 253 → preimage 254 → spill 3 bytes */
+ uint8_t element[253];
+ for (size_t i = 0; i < sizeof(element); i++) {
+ element[i] = (uint8_t) (i * 7);
+ }
+
+ uint8_t hash[32];
+ add_merkle_preimage(mock, element, sizeof(element), hash);
+
+ empty_more_elements_t forge_state = {.elements_len = 1, .n_empty_responses = 0};
+ mock_dispatcher_set_forge_hook(mock, forge_empty_more_elements, &forge_state);
+
+ uint8_t out[512];
+ memset(out, 0xEE, sizeof(out));
+ dispatcher_context_t *dc = mock_dispatcher_get_dc(mock);
+ int result = call_get_merkle_preimage(dc, hash, out, sizeof(out));
+
+ assert_int_equal(result, -9);
+ assert_int_equal(forge_state.n_empty_responses, 1);
+ assert_cleared(out, sizeof(out));
+}
+
/* ---------- Main ---------- */
int main(void) {
@@ -708,6 +767,7 @@ int main(void) {
T(test_get_merkle_preimage_truncated_more),
T(test_get_merkle_preimage_bad_element_size),
T(test_get_merkle_preimage_more_bytes),
+ T(test_get_merkle_preimage_empty_more_elements),
T(test_get_merkle_preimage_internal_node_preimage),
T(test_get_merkle_preimage_bad_prefix),
};
### unit-tests/test_get_preimage.c
@@ -707,6 +707,66 @@ static void test_get_preimage_communication_failure(void **state) {
assert_cleared(out, sizeof(out));
}
+/**
+ * Adversarial: every GET_MORE_ELEMENTS response carries zero elements, so it makes no progress.
+ * This must be rejected immediately, otherwise the host could keep the command alive forever.
+ * The response is forged, as the honest handler would fail once its queue is drained; from the
+ * second request on, the hook simulates a communication failure, so that a regression makes the
+ * test fail rather than hang.
+ */
+typedef struct {
+ uint8_t elements_len;
+ int n_empty_responses;
+} empty_more_elements_t;
+
+static int forge_empty_more_elements(const uint8_t *request_buf,
+ size_t request_len,
+ uint8_t *response_buf,
+ size_t *response_len,
+ void *user_data) {
+ (void) request_len;
+ empty_more_elements_t *s = user_data;
+
+ if (request_buf[0] != CCMD_GET_MORE_ELEMENTS) {
+ return 0; /* anything else is answered honestly */
+ }
+
+ if (++s->n_empty_responses > 1) {
+ return -1;
+ }
+
+ response_buf[0] = 0; /* n_elements */
+ response_buf[1] = s->elements_len;
+ *response_len = 2;
+ return 1;
+}
+
+static void test_get_preimage_empty_more_elements(void **state) {
+ mock_dispatcher_t *mock = *state;
+
+ uint8_t preimage[254]; /* spill = 3 bytes */
+ for (size_t i = 0; i < sizeof(preimage); i++) {
+ preimage[i] = (uint8_t) (i * 7);
+ }
+
+ mock_dispatcher_add_preimage(mock, preimage, sizeof(preimage));
+
+ uint8_t hash[32];
+ compute_sha256(preimage, sizeof(preimage), hash);
+
+ empty_more_elements_t forge_state = {.elements_len = 1, .n_empty_responses = 0};
+ mock_dispatcher_set_forge_hook(mock, forge_empty_more_elements, &forge_state);
+
+ uint8_t out[512];
+ memset(out, 0xEE, sizeof(out));
+ dispatcher_context_t *dc = mock_dispatcher_get_dc(mock);
+ int result = call_get_preimage(dc, hash, out, sizeof(out));
+
+ assert_int_equal(result, -8);
+ assert_int_equal(forge_state.n_empty_responses, 1);
+ assert_cleared(out, sizeof(out));
+}
+
/* ---------- Main ---------- */
int main(void) {
@@ -730,6 +790,7 @@ int main(void) {
T(test_get_preimage_bad_element_size_strict),
T(test_get_preimage_more_bytes_strict),
T(test_get_preimage_communication_failure),
+ T(test_get_preimage_empty_more_elements),
};
#undef T
### unit-tests/test_stream_preimage.c
@@ -741,6 +741,64 @@ static void test_stream_preimage_bad_prefix(void **state) {
assert_int_equal(acc.offset, 0);
}
+/**
+ * Adversarial: every GET_MORE_ELEMENTS response carries zero elements, so it makes no progress.
+ * This must be rejected immediately, otherwise the host could keep the command alive forever.
+ * The response is forged, as the honest handler would fail once its queue is drained; from the
+ * second request on, the hook simulates a communication failure, so that a regression makes the
+ * test fail rather than hang.
+ */
+typedef struct {
+ uint8_t elements_len;
+ int n_empty_responses;
+} empty_more_elements_t;
+
+static int forge_empty_more_elements(const uint8_t *request_buf,
+ size_t request_len,
+ uint8_t *response_buf,
+ size_t *response_len,
+ void *user_data) {
+ (void) request_len;
+ empty_more_elements_t *s = user_data;
+
+ if (request_buf[0] != CCMD_GET_MORE_ELEMENTS) {
+ return 0; /* anything else is answered honestly */
+ }
+
+ if (++s->n_empty_responses > 1) {
+ return -1;
+ }
+
+ response_buf[0] = 0; /* n_elements */
+ response_buf[1] = s->elements_len;
+ *response_len = 2;
+ return 1;
+}
+
+static void test_stream_preimage_empty_more_elements(void **state) {
+ mock_dispatcher_t *mock = *state;
+
+ uint8_t element[253]; /* spill = 3 bytes */
+ for (size_t i = 0; i < sizeof(element); i++) {
+ element[i] = (uint8_t) (i * 7);
+ }
+
+ uint8_t hash[32];
+ add_merkle_preimage(mock, element, sizeof(element), hash);
+
+ empty_more_elements_t forge_state = {.elements_len = 1, .n_empty_responses = 0};
+ mock_dispatcher_set_forge_hook(mock, forge_empty_more_elements, &forge_state);
+
+ stream_accumulator_t acc;
+ memset(&acc, 0, sizeof(acc));
+
+ dispatcher_context_t *dc = mock_dispatcher_get_dc(mock);
+ int result = call_stream_preimage(dc, hash, acc_len_callback, acc_data_callback, &acc);
+
+ assert_int_equal(result, -8);
+ assert_int_equal(forge_state.n_empty_responses, 1);
+}
+
/* ---------- Main ---------- */
int main(void) {
@@ -762,6 +820,7 @@ int main(void) {
T(test_stream_preimage_truncated_more_elements),
T(test_stream_preimage_bad_element_size),
T(test_stream_preimage_more_bytes_than_remaining),
+ T(test_stream_preimage_empty_more_elements),
T(test_stream_preimage_communication_failure),
T(test_stream_preimage_internal_node_preimage),
T(test_stream_preimage_bad_prefix),
### unit-tests/test_wallet.c
@@ -791,8 +791,34 @@ static void test_miniscript_types(void **state) {
Test("thresh(2,dv:older(42),s:pk(@0/**),s:pk(@1/**))", "7663012ab269687c205cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bcac937c20d30199d74fb5a22d47b6e054e2f378cedacffcb89904a61d75d0dbd407143e65ac935287", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG | TESTMODE_P2WSH_INVALID, 12, 4);
// Regression test: thresh 'm' (non-malleable) must require all children to have 'm'.
- // or_b(sha256,a:sha256) has e=1 but m=0 (children lack 's'), so thresh must NOT be NONMAL.
- Test("thresh(1,or_b(sha256(e38990d0c7fc009880a9c07c23842e886c6bbdc964ce6bdd5817ad357335ee6f),a:sha256(d1ec675902ef1633427ca360b290b0b3045a0d9058ddb5e648b4c3c3224c5c68)),a:0)", "?", TESTMODE_VALID, -1, -1);
+ // ltv:or_b(sha256,a:sha256) has e=1 (l: has e = f of t:) but m=0 (the children of or_b lack
+ // 's'), so thresh must NOT be NONMAL.
+ Test("thresh(1,ltv:or_b(sha256(e38990d0c7fc009880a9c07c23842e886c6bbdc964ce6bdd5817ad357335ee6f),a:sha256(d1ec675902ef1633427ca360b290b0b3045a0d9058ddb5e648b4c3c3224c5c68)),a:0)", "?", TESTMODE_VALID, -1, -1);
+
+ // Regression tests: 'l:' and 'u:' can always be dissatisfied via the constant 0 branch, even if
+ // the child can't. The or_d must account for the ops of the multi executed after dissatisfying
+ // the first branch.
+ Test("or_d(utv:pk(@0/**),multi(1,@1/**,@2/**,@3/**))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG | TESTMODE_TAPSCRIPT_INVALID, 11, 4);
+ Test("or_d(ltv:pk(@0/**),multi(1,@1/**,@2/**,@3/**))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG | TESTMODE_TAPSCRIPT_INVALID, 11, 4);
+ // Only the right branch of the or_d exceeds the 201 ops limit
+ Test("or_d(utv:or_i(jjjjjjjjjj:pk(@10/**),jjjjjjjjjj:pk(@11/**)),or_i(jjjjjjjjjjjjj:multi(1,@0/**,@1/**,@2/**,@3/**,@4/**,@5/**,@6/**,@7/**,@8/**,@9/**),jjjjjjjjjjjjj:pk(@12/**)))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG | TESTMODE_TAPSCRIPT_INVALID, 211, -1);
+
+ // Regression tests: the satisfaction of andor(X,Y,Z) via Z executes the dissatisfaction of X,
+ // not of Y. With a 'V' Y (no dissatisfaction), the ops of the multi in Z must still be counted.
+ Test("t:andor(pk(@0/**),v:pk(@1/**),v:multi(1,@2/**,@3/**,@4/**))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG | TESTMODE_TAPSCRIPT_INVALID, 9, 4);
+ // Asymmetric costs: dissatisfying X is more expensive than dissatisfying Y
+ Test("andor(multi(1,@0/**,@1/**),pk(@2/**),multi(1,@3/**,@4/**,@5/**))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG | TESTMODE_TAPSCRIPT_INVALID, 11, 5);
+ // Only the Z branch of the andor exceeds the 201 ops limit
+ Test("t:andor(pk(@10/**),v:or_i(jjjjjjjjjjj:pk(@11/**),jjjjjjjjjjj:pk(@12/**)),v:or_i(jjjjjjjjjjj:multi(1,@0/**,@1/**,@2/**,@3/**,@4/**,@5/**,@6/**,@7/**,@8/**,@9/**),jjjjjjjjjjj:pk(@13/**)))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG | TESTMODE_TAPSCRIPT_INVALID, 202, -1);
+
+ // Regression tests: and_n(X,Y) is andor(X,Y,0). Since 0 has the 's' property, non-malleability
+ // does not require a signature in X or Y; and the dissatisfaction of Y is never executed.
+ Test("and_v(v:pk(@0/**),and_n(un:older(144),sha256(e38990d0c7fc009880a9c07c23842e886c6bbdc964ce6bdd5817ad357335ee6f)))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG, 13, 4);
+ Test("and_n(pk(@0/**),or_i(pk(@1/**),and_b(multi(1,@2/**,@3/**,@4/**,@5/**,@6/**),a:0)))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG | TESTMODE_TAPSCRIPT_INVALID, 12, 4);
+
+ // Regression test: a thresh child containing different kinds of timelocks in separate branches
+ // is not mixing timelocks with itself.
+ Test("thresh(2,pk(@0/**),s:pk(@1/**),anl:or_i(and_v(v:pk(@2/**),older(4194305)),and_v(v:pk(@3/**),older(144))))", "?", TESTMODE_VALID | TESTMODE_NONMAL | TESTMODE_NEEDSIG, 19, 6);
// clang-format on
}Why this scored 72/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.