From ff039399535e52ce700847b30f5ab06656bbc61d Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 18 Nov 2026 13:20:18 +1000 Subject: [PATCH 01/16] ci: validate changelog entries CI accepted malformed Changelog- lines which changelog.py ignored. Match the parser's accepted prefixes so CI and the release notes agree. Changelog-None Co-authored-by: Cursor --- .github/workflows/ci.yaml | 51 +++++++++++++++++++++++++++++++-------- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index fdcd4b8a15eb..7701c3ee389b 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -58,17 +58,48 @@ jobs: echo "Base Ref: $BASE_REF" echo "PR DESCRIPTION: $PR_DESCRIPTION" if [ "$EVENT_NAME" = "pull_request" ]; then - if [[ "$PR_DESCRIPTION" != *"Changelog-None"* && \ - -z "$(git log origin/$BASE_REF..HEAD --oneline --grep='Changelog-')" && \ - "$(git rev-parse --abbrev-ref HEAD)" != "$BASE_REF" ]]; then - echo "::error::'Changelog' entry is missing in all commits, and 'Changelog-None' not specified in the PR description" + on_base=0 + if [ "$(git rev-parse --abbrev-ref HEAD)" = "$BASE_REF" ]; then + on_base=1 + fi + found=0 + invalid=0 + if ! commits=$(git rev-list "origin/${BASE_REF}..HEAD"); then + echo "::error::Cannot list commits origin/${BASE_REF}..HEAD" + exit 1 + fi + # Same shape devtools/changelog.py keeps: class, colon, one space, + # then a nonempty entry. Changelog-None is the opt-out, in a + # commit or in the PR body. Any other Changelog- line is a typo + # which changelog.py would silently drop from the release notes. + valid='^[[:space:]]*Changelog-(Added|Changed|Deprecated|Fixed|Removed|Experimental): [^[:space:]]' + none='^[[:space:]]*Changelog-None([.[:space:]]*$|:)' + while IFS= read -r sha; do + [ -n "$sha" ] || continue + msg=$(git show -s --format=%B "$sha") + shopt -s nocasematch + while IFS= read -r line; do + if [[ "$line" =~ $valid ]] || [[ "$line" =~ $none ]]; then + found=1 + elif [[ "$line" =~ ^[[:space:]]*Changelog- ]]; then + echo "::error::Malformed Changelog line in ${sha}: ${line}" + invalid=1 + fi + done <<< "$msg" + shopt -u nocasematch + done <<< "$commits" + if [ "$invalid" -eq 1 ]; then exit 1 + fi + if [[ "$PR_DESCRIPTION" == *"Changelog-None"* ]]; then + echo "Changelog found in PR description" + elif [ "$found" -eq 1 ]; then + echo "Changelog found in commit range origin/${BASE_REF}..HEAD" + elif [ "$on_base" -eq 1 ]; then + echo "HEAD is ${BASE_REF}; changelog check skipped" else - if [[ "$PR_DESCRIPTION" == *"Changelog-None"* ]]; then - echo "Changelog found in PR description" - else - echo "Changelog found in Commit \"$(git log origin/$BASE_REF..HEAD --oneline --grep='Changelog-')\"" - fi + echo "::error::'Changelog' entry is missing in all commits, and 'Changelog-None' not specified in the PR description" + exit 1 fi else echo "Not a PR event." @@ -101,7 +132,7 @@ jobs: VALGRIND: 0 PYTEST_OPTS: ${{ env.PYTEST_OPTS_BASE }} run: | - uv run make -j $(nproc) check-source BASE_REF="origin/${{ github.base_ref }}" GRPC_BREAKING_BASE_REF="origin/${{ github.base_ref || 'master' }}" CARGO=false CC=devtools/cc-nobuild SUPPRESS_GENERATION=1 + uv run make -j $(nproc) check-source BASE_REF="origin/${{ github.base_ref || 'master' }}" GRPC_BREAKING_BASE_REF="origin/${{ github.base_ref || 'master' }}" CARGO=false CC=devtools/cc-nobuild SUPPRESS_GENERATION=1 - name: Upload test results if: always() uses: actions/upload-artifact@v7 From 9190bd28d1383c307ca6618f27b5d7a3acdfff1b Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 18 Nov 2026 13:20:18 +1000 Subject: [PATCH 02/16] tools: require strict pytest xfail markers A non-strict xfail also passes when the test unexpectedly succeeds. Reject added pytest.mark.xfail decorators without strict=True. Co-authored-by: Cursor --- tests/pytest.ini | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/pytest.ini b/tests/pytest.ini index 03f586d41650..cc1d2b4c10c4 100644 --- a/tests/pytest.ini +++ b/tests/pytest.ini @@ -1,2 +1,3 @@ [pytest] -pythonpath = . \ No newline at end of file +pythonpath = . +xfail_strict = true \ No newline at end of file From fa58d639e3ad01c646af7bfb868cd0a97f460a45 Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 25 Nov 2026 22:54:52 +1000 Subject: [PATCH 03/16] tools: report newly added lines Source checks should reject new problems without requiring contributors to clean up unrelated existing code. Add a helper which reports each line changed or added since the branch diverged from BASE_REF. Co-authored-by: Cursor --- tools/added-lines.sh | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100755 tools/added-lines.sh diff --git a/tools/added-lines.sh b/tools/added-lines.sh new file mode 100755 index 000000000000..22d531bef29b --- /dev/null +++ b/tools/added-lines.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Print "path:line" for every line the working tree adds since the merge +# base of BASE and HEAD, in files matching the pathspecs. A check built on +# this complains about new code only, not about what is already there. +# +# Usage: tools/added-lines.sh BASE [pathspec...] + +set -o pipefail + +base=${1:?usage: added-lines.sh BASE [pathspec...]} +shift + +if ! mergebase=$(git merge-base "$base" HEAD 2> /dev/null); then + echo "added-lines: cannot find a merge base with '$base':" \ + "set BASE_REF to the branch this work is based on" >&2 + exit 1 +fi + +# With -U0 a hunk is only removed and added lines; the +++ header is told +# apart from an added line by coming before the first hunk of its file. +git -c core.quotePath=false diff -U0 --no-color --no-ext-diff --no-prefix "$mergebase" -- "$@" | awk ' +/^diff --git / { header = 1; next } +header && /^\+\+\+ / { file = substr($0, 5); next } +/^@@ / { + header = 0 + split($3, range, ",") + line = substr(range[1], 2) + 0 + next +} +!header && /^\+/ { print file ":" line; line++ } +' || exit 1 + +# A file git does not know yet is new in every line. +git ls-files --others --exclude-standard -- "$@" | while IFS= read -r file; do + awk -v file="$file" '{ print file ":" NR }' "$file" +done From 98e741c01d69ec184b5e1d72dfb1d205d9fdc0d4 Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 18 Nov 2026 15:26:44 +1000 Subject: [PATCH 04/16] tools: reject default labels in enum switches A default label hides the compiler warning when an enum gains a value. Reject added defaults in switches whose cases are enum values. Co-authored-by: Cursor Co-authored-by: Cursor --- Makefile | 7 +- cli/lightning-cli.c | 2 +- closingd/test/run-closingd-negotiation.c | 16 ++- common/wireaddr.c | 56 +++++----- connectd/multiplex.c | 71 ++++++++++-- devtools/create-gossipstore.c | 62 ++++++++++- devtools/print_wire.c | 5 +- gossipd/gossipd.c | 62 ++++++++++- lightningd/peer_htlcs.c | 24 +++- tests/fuzz/fuzz-amount-arith.c | 2 +- tests/fuzz/fuzz-funder-policy.c | 2 - tools/check-switch-default.py | 135 +++++++++++++++++++++++ wire/peer_wire.c | 53 ++++++++- 13 files changed, 432 insertions(+), 65 deletions(-) create mode 100755 tools/check-switch-default.py diff --git a/Makefile b/Makefile index 3aeb0f963210..7010db0bb7cf 100644 --- a/Makefile +++ b/Makefile @@ -711,8 +711,13 @@ check-grpc-breaking: echo "Checking gRPC protos against $$tag"; \ $(BUF) breaking cln-grpc/proto --against ".git#tag=$$tag,subdir=cln-grpc/proto" +# Only lines added since BASE_REF are checked (doc/Makefile sets the +# default): see tools/added-lines.sh. +check-switch-default: + @tools/check-switch-default.py $(BASE_REF) + # This should NOT compile things! -check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking +check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default full-check: check check-source diff --git a/cli/lightning-cli.c b/cli/lightning-cli.c index b1b2acd517ab..fb7da0f75c0f 100644 --- a/cli/lightning-cli.c +++ b/cli/lightning-cli.c @@ -926,7 +926,7 @@ int main(int argc, char *argv[]) json_tok_full_len(result), json_tok_full(resp, result)); break; - default: + case DEFAULT_FORMAT: abort(); } tal_free(ctx); diff --git a/closingd/test/run-closingd-negotiation.c b/closingd/test/run-closingd-negotiation.c index 183c26460d90..ac8486f9630b 100644 --- a/closingd/test/run-closingd-negotiation.c +++ b/closingd/test/run-closingd-negotiation.c @@ -128,22 +128,26 @@ u8 *test_wire_sync_read(const tal_t *ctx, int fd) bool test_wire_sync_write(int fd, const void *msg TAKES) { if (fd == REQ_FD) { - switch (fromwire_peektype(msg)) { + switch ((enum closingd_wire)fromwire_peektype(msg)) { case WIRE_CLOSINGD_RECEIVED_SIGNATURE: { struct bitcoin_signature sig; struct bitcoin_tx *tx; assert(fromwire_closingd_received_signature(tmpctx, msg, &sig, &tx)); bitcoin_txid(tx, &saved_txid); - break; + goto handled; } case WIRE_CLOSINGD_COMPLETE: completed++; - break; + goto handled; case WIRE_CLOSINGD_NOTIFICATION: - break; - default: + goto handled; + case WIRE_CLOSINGD_INIT: + case WIRE_CLOSINGD_RECEIVED_SIGNATURE_REPLY: abort(); } + /* A u16 can hold values outside enum closingd_wire. */ + abort(); + handled:; } else assert(fd == HSM_FD); tal_free_if_taken(msg); @@ -202,7 +206,7 @@ u8 *test_peer_read(const tal_t *ctx, struct per_peer_state *pps) case UPPER_BOUND: fee = offset(high_remote ? first_remote : last_local, false); break; - default: + case AGREE: abort(); } } diff --git a/common/wireaddr.c b/common/wireaddr.c index 1364e4931383..116b115fdb2e 100644 --- a/common/wireaddr.c +++ b/common/wireaddr.c @@ -27,32 +27,11 @@ bool wireaddr_eq_without_port(const struct wireaddr *a, const struct wireaddr *b return memeq(a->addr, a->addrlen, b->addr, b->addrlen); } -enum fromwireaddr_ret fromwire_wireaddr(const u8 **cursor, size_t *max, struct wireaddr *addr) +/* Reads the address and port once addr->type and addr->addrlen are set. */ +static enum fromwireaddr_ret fromwire_wireaddr_rest(const u8 **cursor, + size_t *max, + struct wireaddr *addr) { - addr->type = fromwire_u8(cursor, max); - if (*cursor == NULL) - return FROMWIREADDR_MALFORMED; - - switch (addr->type) { - case ADDR_TYPE_IPV4: - addr->addrlen = 4; - break; - case ADDR_TYPE_IPV6: - addr->addrlen = 16; - break; - case ADDR_TYPE_TOR_V2_REMOVED: - addr->addrlen = TOR_V2_ADDRLEN; - break; - case ADDR_TYPE_TOR_V3: - addr->addrlen = TOR_V3_ADDRLEN; - break; - case ADDR_TYPE_DNS: - addr->addrlen = fromwire_u8(cursor, max); - memset(&addr->addr, 0, sizeof(addr->addr)); - break; - default: - return FROMWIREADDR_UNKNOWN; - } fromwire(cursor, max, addr->addr, addr->addrlen); addr->port = fromwire_u16(cursor, max); @@ -84,6 +63,33 @@ enum fromwireaddr_ret fromwire_wireaddr(const u8 **cursor, size_t *max, struct w return FROMWIREADDR_OK; } +enum fromwireaddr_ret fromwire_wireaddr(const u8 **cursor, size_t *max, struct wireaddr *addr) +{ + addr->type = fromwire_u8(cursor, max); + if (*cursor == NULL) + return FROMWIREADDR_MALFORMED; + + switch (addr->type) { + case ADDR_TYPE_IPV4: + addr->addrlen = 4; + return fromwire_wireaddr_rest(cursor, max, addr); + case ADDR_TYPE_IPV6: + addr->addrlen = 16; + return fromwire_wireaddr_rest(cursor, max, addr); + case ADDR_TYPE_TOR_V2_REMOVED: + addr->addrlen = TOR_V2_ADDRLEN; + return fromwire_wireaddr_rest(cursor, max, addr); + case ADDR_TYPE_TOR_V3: + addr->addrlen = TOR_V3_ADDRLEN; + return fromwire_wireaddr_rest(cursor, max, addr); + case ADDR_TYPE_DNS: + addr->addrlen = fromwire_u8(cursor, max); + memset(&addr->addr, 0, sizeof(addr->addr)); + return fromwire_wireaddr_rest(cursor, max, addr); + } + return FROMWIREADDR_UNKNOWN; +} + void towire_wireaddr(u8 **pptr, const struct wireaddr *addr) { towire_u8(pptr, addr->type); diff --git a/connectd/multiplex.c b/connectd/multiplex.c index b02f1c6d0378..808ee2943598 100644 --- a/connectd/multiplex.c +++ b/connectd/multiplex.c @@ -1114,9 +1114,10 @@ static struct pubkey *extract_revocation_basepoint(const tal_t *ctx, struct pubkey pubkey; t = fromwire_u16(&cursor, &max); + assert(t == WIRE_OPEN_CHANNEL2 || t == WIRE_ACCEPT_CHANNEL2); switch (t) { - case WIRE_OPEN_CHANNEL2: + case WIRE_OPEN_CHANNEL2: /* BOLT #2: * 1. type: 64 (`open_channel2`) * 2. data: @@ -1148,7 +1149,7 @@ static struct pubkey *extract_revocation_basepoint(const tal_t *ctx, + sizeof(u32) + PUBKEY_CMPR_LEN); break; - case WIRE_ACCEPT_CHANNEL2: + case WIRE_ACCEPT_CHANNEL2: /* BOLT #2: * 1. type: 65 (`accept_channel2`) * 2. data: @@ -1174,7 +1175,56 @@ static struct pubkey *extract_revocation_basepoint(const tal_t *ctx, + sizeof(u16) + PUBKEY_CMPR_LEN); break; - default: + case WIRE_WARNING: + case WIRE_INIT: + case WIRE_ERROR: + case WIRE_OPEN_CHANNEL: + case WIRE_ACCEPT_CHANNEL: + case WIRE_FUNDING_CREATED: + case WIRE_FUNDING_SIGNED: + case WIRE_CHANNEL_READY: + case WIRE_SHUTDOWN: + case WIRE_CLOSING_SIGNED: + case WIRE_CLOSING_COMPLETE: + case WIRE_CLOSING_SIG: + case WIRE_UPDATE_ADD_HTLC: + case WIRE_UPDATE_FULFILL_HTLC: + case WIRE_UPDATE_FAIL_HTLC: + case WIRE_UPDATE_FAIL_MALFORMED_HTLC: + case WIRE_PROTOCOL_BATCH_ELEMENT: + case WIRE_START_BATCH: + case WIRE_COMMITMENT_SIGNED: + case WIRE_REVOKE_AND_ACK: + case WIRE_UPDATE_FEE: + case WIRE_UPDATE_BLOCKHEIGHT: + case WIRE_CHANNEL_REESTABLISH: + case WIRE_ANNOUNCEMENT_SIGNATURES: + case WIRE_CHANNEL_ANNOUNCEMENT: + case WIRE_NODE_ANNOUNCEMENT: + case WIRE_CHANNEL_UPDATE: + case WIRE_PING: + case WIRE_PONG: + case WIRE_QUERY_SHORT_CHANNEL_IDS: + case WIRE_REPLY_SHORT_CHANNEL_IDS_END: + case WIRE_QUERY_CHANNEL_RANGE: + case WIRE_REPLY_CHANNEL_RANGE: + case WIRE_GOSSIP_TIMESTAMP_FILTER: + case WIRE_ONION_MESSAGE: + case WIRE_TX_ADD_INPUT: + case WIRE_TX_REMOVE_INPUT: + case WIRE_TX_ADD_OUTPUT: + case WIRE_TX_REMOVE_OUTPUT: + case WIRE_TX_COMPLETE: + case WIRE_TX_SIGNATURES: + case WIRE_TX_INIT_RBF: + case WIRE_TX_ACK_RBF: + case WIRE_TX_ABORT: + case WIRE_PEER_STORAGE: + case WIRE_PEER_STORAGE_RETRIEVAL: + case WIRE_STFU: + case WIRE_SPLICE_INIT: + case WIRE_SPLICE_ACK: + case WIRE_SPLICE_LOCKED: abort(); } @@ -1194,8 +1244,9 @@ static bool extract_funding_created_funding(const u8 *funding_created, t = fromwire_u16(&cursor, &max); - switch (t) { - case WIRE_FUNDING_CREATED: + if (t != WIRE_FUNDING_CREATED) + abort(); + /* BOLT #2: * 1. type: 34 (`funding_created`) * 2. data: @@ -1203,13 +1254,9 @@ static bool extract_funding_created_funding(const u8 *funding_created, * * [`sha256`:`funding_txid`] * * [`u16`:`funding_output_index`] */ - fromwire_pad(&cursor, &max, 32); - fromwire_bitcoin_txid(&cursor, &max, &outp->txid); - outp->n = fromwire_u16(&cursor, &max); - break; - default: - abort(); - } + fromwire_pad(&cursor, &max, 32); + fromwire_bitcoin_txid(&cursor, &max, &outp->txid); + outp->n = fromwire_u16(&cursor, &max); return cursor != NULL; } diff --git a/devtools/create-gossipstore.c b/devtools/create-gossipstore.c index 226324e34f50..cac8e5615c97 100644 --- a/devtools/create-gossipstore.c +++ b/devtools/create-gossipstore.c @@ -166,6 +166,7 @@ int main(int argc, char *argv[]) u8 *inmsg = tal_arr(NULL, u8, msglen); u32 timestamp; struct short_channel_id scid; + bool handled = false; if (!read_all(infd, inmsg, msglen)) err(1, "Only read partial message"); @@ -174,7 +175,7 @@ int main(int argc, char *argv[]) fprintf(stderr, "%s\n", peer_wire_name(fromwire_peektype(inmsg))); - switch (fromwire_peektype(inmsg)) { + switch ((enum peer_wire)fromwire_peektype(inmsg)) { case WIRE_CHANNEL_ANNOUNCEMENT: if (scidsats) { /* We ignore these; we just want scid */ @@ -205,8 +206,8 @@ int main(int argc, char *argv[]) last_announce = inmsg; inmsg = NULL; } + handled = true; break; - case WIRE_CHANNEL_UPDATE: /* We assume update immediately follows announcement */ timestamp = get_update_timestamp(inmsg, &scid); @@ -229,15 +230,66 @@ int main(int argc, char *argv[]) } write_outmsg(outfd, inmsg, timestamp); updates += 1; + handled = true; break; - case WIRE_NODE_ANNOUNCEMENT: timestamp = get_node_announce_timestamp(inmsg); write_outmsg(outfd, inmsg, timestamp); nodes += 1; + handled = true; break; - - default: + case WIRE_WARNING: + case WIRE_INIT: + case WIRE_ERROR: + case WIRE_OPEN_CHANNEL: + case WIRE_ACCEPT_CHANNEL: + case WIRE_FUNDING_CREATED: + case WIRE_FUNDING_SIGNED: + case WIRE_CHANNEL_READY: + case WIRE_SHUTDOWN: + case WIRE_CLOSING_SIGNED: + case WIRE_CLOSING_COMPLETE: + case WIRE_CLOSING_SIG: + case WIRE_UPDATE_ADD_HTLC: + case WIRE_UPDATE_FULFILL_HTLC: + case WIRE_UPDATE_FAIL_HTLC: + case WIRE_UPDATE_FAIL_MALFORMED_HTLC: + case WIRE_PROTOCOL_BATCH_ELEMENT: + case WIRE_START_BATCH: + case WIRE_COMMITMENT_SIGNED: + case WIRE_REVOKE_AND_ACK: + case WIRE_UPDATE_FEE: + case WIRE_UPDATE_BLOCKHEIGHT: + case WIRE_CHANNEL_REESTABLISH: + case WIRE_ANNOUNCEMENT_SIGNATURES: + case WIRE_PING: + case WIRE_PONG: + case WIRE_QUERY_SHORT_CHANNEL_IDS: + case WIRE_REPLY_SHORT_CHANNEL_IDS_END: + case WIRE_QUERY_CHANNEL_RANGE: + case WIRE_REPLY_CHANNEL_RANGE: + case WIRE_GOSSIP_TIMESTAMP_FILTER: + case WIRE_ONION_MESSAGE: + case WIRE_TX_ADD_INPUT: + case WIRE_TX_REMOVE_INPUT: + case WIRE_TX_ADD_OUTPUT: + case WIRE_TX_REMOVE_OUTPUT: + case WIRE_TX_COMPLETE: + case WIRE_TX_SIGNATURES: + case WIRE_TX_INIT_RBF: + case WIRE_TX_ACK_RBF: + case WIRE_TX_ABORT: + case WIRE_PEER_STORAGE: + case WIRE_PEER_STORAGE_RETRIEVAL: + case WIRE_OPEN_CHANNEL2: + case WIRE_ACCEPT_CHANNEL2: + case WIRE_STFU: + case WIRE_SPLICE_INIT: + case WIRE_SPLICE_ACK: + case WIRE_SPLICE_LOCKED: + break; + } + if (!handled) { warnx("Unknown message %u (%s)", fromwire_peektype(inmsg), peer_wire_name(fromwire_peektype(inmsg))); tal_free(inmsg); diff --git a/devtools/print_wire.c b/devtools/print_wire.c index 9afd8f7e5b51..9315383d4b0a 100644 --- a/devtools/print_wire.c +++ b/devtools/print_wire.c @@ -236,15 +236,14 @@ static bool printwire_encoded_short_ids(const u8 **cursor, size_t *plen, size_t printf("["); scids = decode_short_ids(tmpctx, arr); if (scids) { - switch (arr[0]) { + /* decode_short_ids() returned non-NULL, so this is valid. */ + switch ((enum arr_encode_types)arr[0]) { case ARR_UNCOMPRESSED: printf(" (UNCOMPRESSED)"); break; case ARR_ZLIB_DEPRECATED: printf(" (ZLIB)"); break; - default: - abort(); } for (size_t i = 0; i < tal_count(scids); i++) printf(" %s", diff --git a/gossipd/gossipd.c b/gossipd/gossipd.c index 52dfc8bc1d6c..63eb2f84f767 100644 --- a/gossipd/gossipd.c +++ b/gossipd/gossipd.c @@ -463,12 +463,17 @@ static void inject_gossip(struct daemon *daemon, const u8 *msg) u8 *goss; const char *err; struct amount_sat *known_amount; + enum peer_wire type; if (!fromwire_gossipd_addgossip(msg, msg, &goss, &known_amount)) master_badmsg(WIRE_GOSSIPD_ADDGOSSIP, msg); - status_debug("inject_gossip: %s", peer_wire_name(fromwire_peektype(goss))); - switch (fromwire_peektype(goss)) { + type = fromwire_peektype(goss); + status_debug("inject_gossip: %s", peer_wire_name(type)); + + /* Any other message, including unknown types, gets this: */ + err = tal_fmt(tmpctx, "unknown gossip type %i", type); + switch (type) { case WIRE_CHANNEL_ANNOUNCEMENT: err = gossmap_manage_channel_announcement(tmpctx, daemon->gm, @@ -488,9 +493,56 @@ static void inject_gossip(struct daemon *daemon, const u8 *msg) status_debug("update %s gave error %s", tal_hex(tmpctx, goss), err); break; - default: - err = tal_fmt(tmpctx, "unknown gossip type %i", - fromwire_peektype(goss)); + case WIRE_WARNING: + case WIRE_INIT: + case WIRE_ERROR: + case WIRE_OPEN_CHANNEL: + case WIRE_ACCEPT_CHANNEL: + case WIRE_FUNDING_CREATED: + case WIRE_FUNDING_SIGNED: + case WIRE_CHANNEL_READY: + case WIRE_SHUTDOWN: + case WIRE_CLOSING_SIGNED: + case WIRE_CLOSING_COMPLETE: + case WIRE_CLOSING_SIG: + case WIRE_UPDATE_ADD_HTLC: + case WIRE_UPDATE_FULFILL_HTLC: + case WIRE_UPDATE_FAIL_HTLC: + case WIRE_UPDATE_FAIL_MALFORMED_HTLC: + case WIRE_PROTOCOL_BATCH_ELEMENT: + case WIRE_START_BATCH: + case WIRE_COMMITMENT_SIGNED: + case WIRE_REVOKE_AND_ACK: + case WIRE_UPDATE_FEE: + case WIRE_UPDATE_BLOCKHEIGHT: + case WIRE_CHANNEL_REESTABLISH: + case WIRE_ANNOUNCEMENT_SIGNATURES: + case WIRE_PING: + case WIRE_PONG: + case WIRE_QUERY_SHORT_CHANNEL_IDS: + case WIRE_REPLY_SHORT_CHANNEL_IDS_END: + case WIRE_QUERY_CHANNEL_RANGE: + case WIRE_REPLY_CHANNEL_RANGE: + case WIRE_GOSSIP_TIMESTAMP_FILTER: + case WIRE_ONION_MESSAGE: + case WIRE_TX_ADD_INPUT: + case WIRE_TX_REMOVE_INPUT: + case WIRE_TX_ADD_OUTPUT: + case WIRE_TX_REMOVE_OUTPUT: + case WIRE_TX_COMPLETE: + case WIRE_TX_SIGNATURES: + case WIRE_TX_INIT_RBF: + case WIRE_TX_ACK_RBF: + case WIRE_TX_ABORT: + case WIRE_PEER_STORAGE: + case WIRE_PEER_STORAGE_RETRIEVAL: + case WIRE_OPEN_CHANNEL2: + case WIRE_ACCEPT_CHANNEL2: + case WIRE_STFU: + case WIRE_SPLICE_INIT: + case WIRE_SPLICE_ACK: + case WIRE_SPLICE_LOCKED: + break; } /* FIXME: Make this an optional string in gossipd_addgossip_reply */ diff --git a/lightningd/peer_htlcs.c b/lightningd/peer_htlcs.c index c14bff6435da..504d93154346 100644 --- a/lightningd/peer_htlcs.c +++ b/lightningd/peer_htlcs.c @@ -2854,6 +2854,8 @@ void peer_got_revoke(struct channel *channel, const u8 *msg) local_fail_in_htlc(hin, failmsgs[i]); failtype = fromwire_peektype(failmsgs[i]); + /* Anything else, including unknown values, gets this: */ + reason = FORWARD_FAIL_UNKNOWN; switch (failtype) { case WIRE_PERMANENT_CHANNEL_FAILURE: reason = FORWARD_FAIL_CHANNEL_SHUTTING_DOWN; @@ -2861,8 +2863,26 @@ void peer_got_revoke(struct channel *channel, const u8 *msg) case WIRE_INVALID_ONION_BLINDING: reason = FORWARD_FAIL_INVALID_ONION; break; - default: - reason = FORWARD_FAIL_UNKNOWN; + case WIRE_TEMPORARY_NODE_FAILURE: + case WIRE_PERMANENT_NODE_FAILURE: + case WIRE_REQUIRED_NODE_FEATURE_MISSING: + case WIRE_INVALID_ONION_VERSION: + case WIRE_INVALID_ONION_HMAC: + case WIRE_INVALID_ONION_KEY: + case WIRE_TEMPORARY_CHANNEL_FAILURE: + case WIRE_REQUIRED_CHANNEL_FEATURE_MISSING: + case WIRE_UNKNOWN_NEXT_PEER: + case WIRE_AMOUNT_BELOW_MINIMUM: + case WIRE_FEE_INSUFFICIENT: + case WIRE_INCORRECT_CLTV_EXPIRY: + case WIRE_EXPIRY_TOO_SOON: + case WIRE_INCORRECT_OR_UNKNOWN_PAYMENT_DETAILS: + case WIRE_FINAL_INCORRECT_CLTV_EXPIRY: + case WIRE_FINAL_INCORRECT_HTLC_AMOUNT: + case WIRE_CHANNEL_DISABLED: + case WIRE_EXPIRY_TOO_FAR: + case WIRE_INVALID_ONION_PAYLOAD: + case WIRE_MPP_TIMEOUT: break; } } else diff --git a/tests/fuzz/fuzz-amount-arith.c b/tests/fuzz/fuzz-amount-arith.c index 4fb0b720590e..6e8d7a31aa02 100644 --- a/tests/fuzz/fuzz-amount-arith.c +++ b/tests/fuzz/fuzz-amount-arith.c @@ -231,7 +231,7 @@ void run(const uint8_t *data, size_t size) { } break; } - default: + case OP_COUNT: assert(false && "Unknown operation!"); } } diff --git a/tests/fuzz/fuzz-funder-policy.c b/tests/fuzz/fuzz-funder-policy.c index 25667fbe2354..3369a5465fa0 100644 --- a/tests/fuzz/fuzz-funder-policy.c +++ b/tests/fuzz/fuzz-funder-policy.c @@ -68,8 +68,6 @@ static struct test_case *new_test_case(const tal_t *ctx, const u8 **cursor, size case FIXED: tcase->policy.mod %= MAX_SATS + 1; break; - default: - assert(false && "invalid policy"); } tcase->policy.min_their_funding = fromwire_amount_sat_bounded(cursor, max); tcase->policy.max_their_funding = fromwire_amount_sat_bounded(cursor, max); diff --git a/tools/check-switch-default.py b/tools/check-switch-default.py new file mode 100755 index 000000000000..a649990424ba --- /dev/null +++ b/tools/check-switch-default.py @@ -0,0 +1,135 @@ +#!/usr/bin/env python3 +"""Flag a `default:` label added to a switch over an enum. + +Without a default, the compiler warns about every switch which does not +handle a newly added enumerator. + +Only added lines are checked (see tools/added-lines.sh), and only switches +where some case label is an enumerator: one declared in a tracked source +file, or a WIRE_ name, since the wire headers are generated. A switch over +errno values or address families may keep its default. +""" +import os +import re +import subprocess +import sys + +PATHSPECS = ['*.c', '*.h', ':(exclude)ccan/', ':(exclude)contrib/'] + +# Comments, strings and character constants: none of them hold code. +NOT_CODE = re.compile(r'''//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*' ''', re.S | re.X) +ENUM = re.compile(r'\benum\b[^;{}()]*\{([^{}]*)\}') +ENUMERATOR = re.compile(r'\s*([A-Za-z_]\w*)') +SWITCH = re.compile(r'\bswitch\s*\(') +CASE = re.compile(r'\bcase\s+([A-Za-z_]\w*)\s*:') +DEFAULT = re.compile(r'\bdefault\s*:') + + +def code_only(text): + """Blank out whatever is not code, keeping every line where it was.""" + return NOT_CODE.sub(lambda m: re.sub(r'[^\n]', ' ', m.group()), text) + + +def read(path): + with open(path, errors='replace') as f: + return f.read() + + +def enumerators(): + """Every enumerator declared in a tracked C file.""" + names = set() + tracked = subprocess.run(['git', 'ls-files', '-z', '--', '*.c', '*.h'], + check=True, stdout=subprocess.PIPE, text=True) + for path in tracked.stdout.split('\0'): + if not os.path.isfile(path): + continue + text = read(path) + if 'enum' not in text: + continue + for body in ENUM.findall(code_only(text)): + body = re.sub(r'^\s*#.*$', '', body, flags=re.M) + for item in body.split(','): + name = ENUMERATOR.match(item) + if name: + names.add(name.group(1)) + return names + + +def closing(code, start, opener, closer): + """Offset just past the bracket which closes the one at start.""" + depth = 0 + for i in range(start, len(code)): + if code[i] == opener: + depth += 1 + elif code[i] == closer: + depth -= 1 + if depth == 0: + return i + 1 + return None + + +def switch_bodies(code): + """(start, end) offsets of the braces of each switch statement.""" + bodies = [] + for switch in SWITCH.finditer(code): + after = closing(code, switch.end() - 1, '(', ')') + if after is None: + continue + brace = code.find('{', after) + if brace == -1 or code[after:brace].strip(): + continue + end = closing(code, brace, '{', '}') + if end is not None: + bodies.append((brace, end)) + return bodies + + +def innermost(bodies, offset): + inside = [b for b in bodies if b[0] < offset < b[1]] + return max(inside, default=None) + + +def enum_defaults(code, names): + """(line, enumerator) for each default: in a switch over an enum.""" + bodies = switch_bodies(code) + for default in DEFAULT.finditer(code): + body = innermost(bodies, default.start()) + if body is None: + continue + for case in CASE.finditer(code, body[0], body[1]): + label = case.group(1) + if innermost(bodies, case.start()) != body: + continue + if label in names or label.startswith('WIRE_'): + yield code.count('\n', 0, default.start()) + 1, label + break + + +def main(): + base = sys.argv[1] if len(sys.argv) > 1 else 'master' + helper = os.path.join(os.path.dirname(sys.argv[0]), 'added-lines.sh') + lines = subprocess.run([helper, base] + PATHSPECS, + check=True, stdout=subprocess.PIPE, text=True) + added = {} + for entry in lines.stdout.splitlines(): + path, line = entry.rsplit(':', 1) + added.setdefault(path, set()).add(int(line)) + + names = None + failed = False + for path in sorted(added): + code = code_only(read(path)) + if not DEFAULT.search(code): + continue + if names is None: + names = enumerators() + for line, label in enum_defaults(code, names): + if line in added[path]: + print(f'{path}:{line}: default: in a switch over an enum ({label}, ...):' + ' list every case, so the compiler warns when one is added') + failed = True + sys.exit(1 if failed else 0) + + +if __name__ == '__main__': + main() diff --git a/wire/peer_wire.c b/wire/peer_wire.c index d35eb6330ff6..71d2f9179ff1 100644 --- a/wire/peer_wire.c +++ b/wire/peer_wire.c @@ -71,9 +71,58 @@ bool is_oversized_gossip_msg(const u8 *msg) return tal_bytelen(msg) > MAX_CHANNEL_UPDATE_LEN; case WIRE_NODE_ANNOUNCEMENT: return tal_bytelen(msg) > MAX_NODE_ANNOUNCEMENT_LEN; - default: - return false; + case WIRE_WARNING: + case WIRE_INIT: + case WIRE_ERROR: + case WIRE_OPEN_CHANNEL: + case WIRE_ACCEPT_CHANNEL: + case WIRE_FUNDING_CREATED: + case WIRE_FUNDING_SIGNED: + case WIRE_CHANNEL_READY: + case WIRE_SHUTDOWN: + case WIRE_CLOSING_SIGNED: + case WIRE_CLOSING_COMPLETE: + case WIRE_CLOSING_SIG: + case WIRE_UPDATE_ADD_HTLC: + case WIRE_UPDATE_FULFILL_HTLC: + case WIRE_UPDATE_FAIL_HTLC: + case WIRE_UPDATE_FAIL_MALFORMED_HTLC: + case WIRE_PROTOCOL_BATCH_ELEMENT: + case WIRE_START_BATCH: + case WIRE_COMMITMENT_SIGNED: + case WIRE_REVOKE_AND_ACK: + case WIRE_UPDATE_FEE: + case WIRE_UPDATE_BLOCKHEIGHT: + case WIRE_CHANNEL_REESTABLISH: + case WIRE_ANNOUNCEMENT_SIGNATURES: + case WIRE_PING: + case WIRE_PONG: + case WIRE_QUERY_SHORT_CHANNEL_IDS: + case WIRE_REPLY_SHORT_CHANNEL_IDS_END: + case WIRE_QUERY_CHANNEL_RANGE: + case WIRE_REPLY_CHANNEL_RANGE: + case WIRE_GOSSIP_TIMESTAMP_FILTER: + case WIRE_ONION_MESSAGE: + case WIRE_TX_ADD_INPUT: + case WIRE_TX_REMOVE_INPUT: + case WIRE_TX_ADD_OUTPUT: + case WIRE_TX_REMOVE_OUTPUT: + case WIRE_TX_COMPLETE: + case WIRE_TX_SIGNATURES: + case WIRE_TX_INIT_RBF: + case WIRE_TX_ACK_RBF: + case WIRE_TX_ABORT: + case WIRE_PEER_STORAGE: + case WIRE_PEER_STORAGE_RETRIEVAL: + case WIRE_OPEN_CHANNEL2: + case WIRE_ACCEPT_CHANNEL2: + case WIRE_STFU: + case WIRE_SPLICE_INIT: + case WIRE_SPLICE_ACK: + case WIRE_SPLICE_LOCKED: + break; } + return false; } bool is_msg_for_gossipd(const u8 *cursor) From e6e6f93eb13080d60651398700a82f8f9f7a86d3 Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 18 Nov 2026 15:26:44 +1000 Subject: [PATCH 05/16] tools: check every commit in a branch Add make check-commits to build each commit and run check-source, unit tests and touched integration tests. check-commits-full runs all integration tests instead. Co-authored-by: Cursor --- Makefile | 9 ++ tools/check-commits.sh | 181 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 190 insertions(+) create mode 100755 tools/check-commits.sh diff --git a/Makefile b/Makefile index 7010db0bb7cf..6345fde2d206 100644 --- a/Makefile +++ b/Makefile @@ -721,6 +721,15 @@ check-source: check-makefile check-whitespace check-spelling check-python-flake8 full-check: check check-source +# Build, check-source, unit tests and touched integration tests on each +# commit since BASE_REF: see tools/check-commits.sh. +check-commits: + @uv run tools/check-commits.sh $(BASE_REF) + +# The same, with the whole integration suite on every commit. +check-commits-full: + @CHECK_COMMITS_PYTEST=all uv run tools/check-commits.sh $(BASE_REF) + # Simple target to be used on CI systems to check that all the derived # files were checked in and updated. It depends on the generated # targets, and checks if any of the tracked files changed. If they did diff --git a/tools/check-commits.sh b/tools/check-commits.sh new file mode 100755 index 000000000000..d0c3dbe2e172 --- /dev/null +++ b/tools/check-commits.sh @@ -0,0 +1,181 @@ +#!/usr/bin/env bash +# Check each commit in BASE..HEAD on its own, oldest first: build, +# check-source, unit tests, then the integration test files that commit +# touches. Run it through make, so the tools come from the uv environment: +# +# make check-commits [BASE_REF=origin/master] +# make check-commits-full # whole integration suite on every commit +# +# The branch is not rewritten. Each commit is checked out detached and the +# original HEAD is restored afterwards, so tracked files must be clean. +# +# A commit that passes is recorded by tree, parent tree and configuration, +# so a rerun after fixing a later commit skips the earlier ones. +# +# Environment: +# CHECK_COMMITS_PYTEST touched (default), all, or none +# CHECK_COMMITS_SKIP_TIP 1 to leave out the last commit +# CHECK_COMMITS_CACHE file listing passed commits (default: in .git; +# /dev/null to disable) +# CHECK_COMMITS_LOGDIR where step logs go (default: a new temp dir) +# CHECK_COMMITS_JOBS parallel make jobs (default: number of CPUs) +# PYTEST_PAR pytest workers (default: CHECK_COMMITS_JOBS) + +set -u + +orig= + +die() { + echo "check-commits: $*" >&2 + exit 1 +} + +tracked_changes() { + git status --porcelain --untracked-files=no --ignore-submodules=all +} + +submodule_changes() { + # shellcheck disable=SC2016 # Expanded by the shell in each submodule. + git submodule foreach --quiet --recursive \ + 'test -z "$(git status --porcelain)" || echo "$displaypath"' +} + +update_submodules() { + git submodule sync --quiet --recursive + git submodule update --quiet --init --recursive +} + +restore_head() { + if [ -n "$orig" ] && ! git checkout -q "$orig"; then + echo "check-commits: could not return to $orig, HEAD is still detached" >&2 + elif [ -n "$orig" ] && ! update_submodules; then + echo "check-commits: returned to $orig, but could not restore its submodules" >&2 + fi +} + +# Tracked files that a step rewrites are stale in the commit, and would +# block the checkout of the next one. +require_clean() { + if [ -n "$(tracked_changes)" ]; then + echo "check-commits: $1 changed tracked files, so this commit has them stale:" >&2 + tracked_changes >&2 + return 1 + fi +} + +# Run one step with its output in a log, and show the tail if it fails. +step() { + local name=$1 log + shift + log="$logdir/$label-$name.log" + printf ' %-12s ' "$name" + if "$@" > "$log" 2>&1; then + echo ok + return 0 + fi + echo FAILED + tail -n 60 "$log" + echo "check-commits: $name failed, full log in $log" >&2 + return 1 +} + +check_commit() { + local sha=$1 tests + + step build make -j "$jobs" || return 1 + require_clean "the build" || return 1 + step check-source make -j "$jobs" check-source BASE_REF="$base" || return 1 + step check-units make -j "$jobs" check-units || return 1 + + case "$pytest_mode" in + none) + ;; + all) + step pytest make pytest || return 1 + ;; + touched) + tests=$(git diff-tree --no-commit-id --name-only -r --diff-filter=d "$sha" -- 'tests/test_*.py' | tr '\n' ' ') + if [ -n "$tests" ]; then + step pytest make pytest PYTEST_TESTS="$tests" || return 1 + fi + ;; + esac + require_clean "the checks" +} + +# Everything runs from main, so bash has read the whole file before the +# first checkout: an older commit may not have this script. +main() { + local base commits total config messages key sha n=0 skipped=0 + + cd "$(git rev-parse --show-toplevel)" || exit 1 + + base=${1:-origin/master} + pytest_mode=${CHECK_COMMITS_PYTEST:-touched} + case "$pytest_mode" in + touched|all|none) + ;; + *) + die "CHECK_COMMITS_PYTEST must be touched, all or none" + ;; + esac + jobs=${CHECK_COMMITS_JOBS:-$(getconf _NPROCESSORS_ONLN)} + export PYTEST_PAR=${PYTEST_PAR:-$jobs} + cache=${CHECK_COMMITS_CACHE:-$(git rev-parse --git-path check-commits-passed)} + # The sub-makes take their options from here, not from a make that ran us. + unset MAKEFLAGS MFLAGS MAKELEVEL + + git rev-parse -q --verify "$base^{commit}" > /dev/null || die "no such base: $base" + [ -z "$(tracked_changes)" ] || die "tracked files have changes, commit or stash them first" + [ -z "$(submodule_changes)" ] || die "submodules have changes, commit or stash them first" + if git submodule status --recursive | grep -q '^[+U]'; then + die "a submodule is not at the revision recorded by HEAD" + fi + + commits=$(git rev-list --reverse "$base..HEAD") || exit 1 + if [ "${CHECK_COMMITS_SKIP_TIP:-0}" = 1 ]; then + commits=$(printf '%s\n' "$commits" | sed '$d') + fi + if [ -z "$commits" ]; then + echo "check-commits: no commits to check in $base..HEAD" + exit 0 + fi + total=$(printf '%s\n' "$commits" | wc -l | tr -d ' ') + + logdir=${CHECK_COMMITS_LOGDIR:-$(mktemp -d "${TMPDIR:-/tmp}/check-commits.XXXXXX")} + mkdir -p "$logdir" || exit 1 + + orig=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD) + trap restore_head EXIT + trap 'exit 130' INT TERM + + for sha in $commits; do + n=$((n + 1)) + label=$(printf '%02d-%s' "$n" "$(git rev-parse --short "$sha")") + echo "[$n/$total] $(git log -1 --format='%h %s' "$sha")" + + config=$(git hash-object config.vars 2> /dev/null || echo unconfigured) + messages=$(git log --reverse --format='%B%x00' "$base..$sha" | git hash-object --stdin) + key="$(git rev-parse "$sha^{tree}") $(git rev-parse -q --verify "$sha^^{tree}" || echo root) $pytest_mode $config $messages" + if grep -qxF "$key" "$cache" 2> /dev/null; then + echo " already passed" + skipped=$((skipped + 1)) + continue + fi + + git checkout -q --detach "$sha" || exit 1 + if ! step submodules update_submodules; then + echo "check-commits: FAILED to update submodules at $(git log -1 --format='%h %s' "$sha")" >&2 + exit 1 + fi + if ! check_commit "$sha"; then + echo "check-commits: FAILED at $(git log -1 --format='%h %s' "$sha")" >&2 + exit 1 + fi + echo "$key" >> "$cache" + done + + echo "check-commits: all $total commits pass ($skipped already passed in an earlier run)" +} + +main "$@" From 1908fd45e7eb33917da1acf5bd5f97e5cacbc0ec Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 18 Nov 2026 15:26:44 +1000 Subject: [PATCH 06/16] ci: add opt-in per-commit checks Add a workflow which maintainers can enable with a repository variable, a PR label or workflow_dispatch. It enables Rust only when the PR touches Rust inputs. Co-authored-by: Cursor --- .github/workflows/per-commit.yaml | 126 ++++++++++++++++++++++++++++++ 1 file changed, 126 insertions(+) create mode 100644 .github/workflows/per-commit.yaml diff --git a/.github/workflows/per-commit.yaml b/.github/workflows/per-commit.yaml new file mode 100644 index 000000000000..d46ab543b71c --- /dev/null +++ b/.github/workflows/per-commit.yaml @@ -0,0 +1,126 @@ +--- +name: Per-commit checks +# Builds and tests every commit of a PR except the last, which the main CI +# workflow already covers. +# +# Off by default. A maintainer turns it on for all PRs by setting the +# repository variable PER_COMMIT_CHECKS to "true", for one PR by adding the +# "per-commit-checks" label, or runs it by hand on a branch. +on: + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + inputs: + base: + description: Branch the commits are compared against + default: master +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + # Reduce size, as in the main CI workflow + RUST_PROFILE: small + SLOW_MACHINE: 1 + SCCACHE_GHA_ENABLED: "true" + BASE_REF: ${{ github.base_ref || inputs.base }} + PASSED_KEY: check-commits-${{ github.event.pull_request.number || github.ref_name }} + +jobs: + per-commit: + name: Build and test each commit + runs-on: ubuntu-24.04 + timeout-minutes: 120 + if: >- + github.event_name == 'workflow_dispatch' || + (github.event.action == 'labeled' && + github.event.label.name == 'per-commit-checks') || + (github.event.action != 'labeled' && + (vars.PER_COMMIT_CHECKS == 'true' || + contains(github.event.pull_request.labels.*.name, 'per-commit-checks'))) + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + submodules: recursive + + - name: Set up Python 3.10 + uses: actions/setup-python@v7 + with: + python-version: "3.10" + + - name: Install uv + uses: astral-sh/setup-uv@v10.3.2 + + - uses: actions/cache@v6 + with: + path: ~/ci-cache + key: apt-${{ runner.os }} + + - name: Install dependencies + run: | + bash -x .github/scripts/setup.sh + # check-source checks BOLT quotes + git clone https://github.com/lightning/bolts.git ../bolts + + - name: Setup sccache + uses: mozilla-actions/sccache-action@v0.0.11 + + # Commits that passed on an earlier push of this PR are not rechecked. + - name: Restore list of commits that passed + uses: actions/cache/restore@v6 + with: + path: ~/check-commits + key: ${{ env.PASSED_KEY }}-${{ github.run_id }}-${{ github.run_attempt }} + restore-keys: | + ${{ env.PASSED_KEY }}- + + # The Rust build is the slow part, and the main CI workflow builds the + # last commit with it anyway. + - name: Configure + run: | + git fetch origin "$BASE_REF" + rust=--disable-rust + if ! git diff --quiet "origin/$BASE_REF...HEAD" -- '*.rs' '*Cargo.toml' Cargo.lock cln-grpc/ cln-rpc/ contrib/msggen/ doc/schemas/; then + rust=--enable-rust + fi + ./configure --enable-debugbuild --disable-valgrind "$rust" CC="sccache gcc" + + - name: Check each commit + env: + COMPAT: 1 + RUSTC_WRAPPER: sccache + PYTEST_OPTS: --timeout=1800 + CHECK_COMMITS_SKIP_TIP: 1 + CHECK_COMMITS_LOGDIR: ${{ runner.temp }}/check-commits-logs + run: | + mkdir -p ~/check-commits + touch ~/check-commits/passed + export CHECK_COMMITS_CACHE=~/check-commits/passed + export GRPC_BREAKING_BASE_REF="origin/$BASE_REF" + # Use the base branch's script, so a PR branched before a change + # to it is checked the same way as every other PR. + script="$RUNNER_TEMP/check-commits.sh" + git show "origin/$BASE_REF:tools/check-commits.sh" > "$script" 2>/dev/null || cp tools/check-commits.sh "$script" + chmod +x "$script" + sg wireshark "uv run eatmydata $script origin/$BASE_REF" + + - name: Save list of commits that passed + if: always() + uses: actions/cache/save@v6 + with: + path: ~/check-commits + key: ${{ env.PASSED_KEY }}-${{ github.run_id }}-${{ github.run_attempt }} + + - name: Upload step logs + if: failure() + uses: actions/upload-artifact@v7 + with: + name: check-commits-logs + path: ${{ runner.temp }}/check-commits-logs + if-no-files-found: ignore From b2e74fbc50b4eb54cc8cfb4d2d6a49136b2b9fee Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 18 Nov 2026 17:04:51 +1000 Subject: [PATCH 07/16] tools: reject comments which will go stale Comments should describe the code a reader can see. Reject added comments which narrate the change, describe removed code, cite a ticket or review, or point to a line number. Co-authored-by: Cursor --- Makefile | 5 +- tools/check-comments.py | 121 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 125 insertions(+), 1 deletion(-) create mode 100755 tools/check-comments.py diff --git a/Makefile b/Makefile index 6345fde2d206..07743bf82a33 100644 --- a/Makefile +++ b/Makefile @@ -716,8 +716,11 @@ check-grpc-breaking: check-switch-default: @tools/check-switch-default.py $(BASE_REF) +check-comments: + @tools/check-comments.py $(BASE_REF) + # This should NOT compile things! -check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default +check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments full-check: check check-source diff --git a/tools/check-comments.py b/tools/check-comments.py new file mode 100755 index 000000000000..e84e6a1c3471 --- /dev/null +++ b/tools/check-comments.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Flag added comments which will go stale. + +A comment describes the code beside it, to a reader who has never seen +any other version of the file. What a change fixed, what the code used to +do, and which pull request or review asked for it belong in the commit +message: in a comment they are out of date as soon as the commit lands. + +Only added lines are checked (see tools/added-lines.sh). BOLT quotes are +left alone. +""" +import io +import os +import re +import subprocess +import sys +import tokenize + +PATHSPECS = ['*.c', '*.h', '*.py', ':(exclude)ccan/', + ':(exclude)*gen.c', ':(exclude)*gen.h', + ':(exclude)*_pb2*.py', ':(exclude)*grpc2py.py'] + +STALE = [ + (re.compile(r'\b(the|this) fix\b|\bthis (commit|pr|patch|change)\b' + r'|\b(previous|next|earlier|later|follow-?up) (commit|pr|patch)\b', re.I), + 'describes the change, not the code: put that in the commit message'), + (re.compile(r'\bused to be\b|\b(we|it|they|there|this|that|which|\w+\(\)) used to\b' + r'|\b(old|previous|former|original|earlier) (code|implementation|behaviou?r|logic)\b' + r'|\brefactor(ed|ing)?\b|\brenamed (from|to)\b', re.I), + 'describes code which is gone: say what this code does, or what breaks without it'), + (re.compile(r'github\.com/ElementsProject/lightning/(pull|issues)/\d+' + r'|\b(pr|mr|pull request|issue)\s*[#!]?\d+\b' + r'|(? 1 else 'master' + helper = os.path.join(os.path.dirname(sys.argv[0]), 'added-lines.sh') + lines = subprocess.run([helper, base] + PATHSPECS, + check=True, stdout=subprocess.PIPE, text=True) + added = {} + for entry in lines.stdout.splitlines(): + path, line = entry.rsplit(':', 1) + added.setdefault(path, set()).add(int(line)) + + failed = False + for path in sorted(added): + with open(path, errors='replace') as f: + text = f.read() + for line, complaint in sorted(problems(path, text, added[path])): + print(f'{path}:{line}: {complaint}') + failed = True + sys.exit(1 if failed else 0) + + +if __name__ == '__main__': + main() From 85b9d6990108e9262075bd2e3aee58a7e3626e9b Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 18 Nov 2026 17:05:00 +1000 Subject: [PATCH 08/16] tools: cap added comment length Limit comments inside code to 4 lines and comments at the left margin to 8. BOLT quotes and tutorial comments are exempt. Co-authored-by: Cursor --- tools/check-comments.py | 46 +++++++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 13 deletions(-) diff --git a/tools/check-comments.py b/tools/check-comments.py index e84e6a1c3471..786449b9eff4 100755 --- a/tools/check-comments.py +++ b/tools/check-comments.py @@ -1,13 +1,15 @@ #!/usr/bin/env python3 -"""Flag added comments which will go stale. +"""Flag added comments which are long, or which will go stale. A comment describes the code beside it, to a reader who has never seen any other version of the file. What a change fixed, what the code used to do, and which pull request or review asked for it belong in the commit message: in a comment they are out of date as soon as the commit lands. +And a comment which needs many lines usually explains code which should be +simpler. Only added lines are checked (see tools/added-lines.sh). BOLT quotes are -left alone. +left alone, and the /*~ walkthrough comments may be any length. """ import io import os @@ -20,6 +22,11 @@ ':(exclude)*gen.c', ':(exclude)*gen.h', ':(exclude)*_pb2*.py', ':(exclude)*grpc2py.py'] +# A comment at the left margin documents a function or a type; an indented +# one is in the middle of the code it explains. +MAX_LINES = 8 +MAX_INDENTED_LINES = 4 + STALE = [ (re.compile(r'\b(the|this) fix\b|\bthis (commit|pr|patch|change)\b' r'|\b(previous|next|earlier|later|follow-?up) (commit|pr|patch)\b', re.I), @@ -42,9 +49,14 @@ # Comments, and the strings and character constants which could hold "//". C_TOKEN = re.compile(r'''//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*' ''', re.S | re.X) +# A comment which starts as a BOLT quote is exempt: check_quotes.py verifies +# it against the spec, so it cannot drift. The word BOLT anywhere else is +# not an exemption, since check_quotes.py never looks at those comments. +BOLT_QUOTE = re.compile(r'(/\* |// |# )BOLT') + def c_comments(text): - """(first line, lines) of each comment; a run of // lines is one.""" + """(first line, lines, indented) of each comment; a run of // lines is one.""" comments = [] for token in C_TOKEN.finditer(text): body = token.group() @@ -52,18 +64,19 @@ def c_comments(text): continue first = text.count('\n', 0, token.start()) + 1 lines = body.split('\n') - alone = not text[text.rfind('\n', 0, token.start()) + 1:token.start()].strip() + before = text[text.rfind('\n', 0, token.start()) + 1:token.start()] + alone = not before.strip() prev = comments[-1] if comments else None - if (body.startswith('//') and alone and prev and prev[2] + if (body.startswith('//') and alone and prev and prev[3] and prev[0] + len(prev[1]) == first): prev[1].extend(lines) continue - comments.append([first, lines, body.startswith('//') and alone]) - return [(first, lines) for first, lines, _ in comments] + comments.append([first, lines, before != '', body.startswith('//') and alone]) + return [tuple(comment[:3]) for comment in comments] def py_comments(text): - """(first line, lines) of each comment; a run of # lines is one.""" + """(first line, lines, indented) of each comment; a run of # lines is one.""" comments = [] try: tokens = list(tokenize.generate_tokens(io.StringIO(text).readline)) @@ -75,19 +88,26 @@ def py_comments(text): line = token.start[0] alone = not token.line[:token.start[1]].strip() prev = comments[-1] if comments else None - if alone and prev and prev[2] and prev[0] + len(prev[1]) == line: + if alone and prev and prev[3] and prev[0] + len(prev[1]) == line: prev[1].append(token.string) continue - comments.append([line, [token.string], alone]) - return [(first, lines) for first, lines, _ in comments] + comments.append([line, [token.string], token.start[1] != 0, alone]) + return [tuple(comment[:3]) for comment in comments] def problems(path, text, added): """(line, complaint) for each added comment line which breaks a rule.""" comments = py_comments(text) if path.endswith('.py') else c_comments(text) - for first, lines in comments: - if 'BOLT' in '\n'.join(lines): + for first, lines, indented in comments: + whole = '\n'.join(lines) + new = [line for line in range(first, first + len(lines)) if line in added] + if not new or BOLT_QUOTE.match(whole): continue + limit = MAX_INDENTED_LINES if indented else MAX_LINES + if len(lines) > limit and not whole.startswith('/*~'): + where = 'inside code' if indented else 'at the left margin' + yield new[0], (f'comment is {len(lines)} lines long (limit {limit} {where}):' + ' keep it short, and let simpler code say the rest') for line, content in enumerate(lines, first): if line not in added: continue From f0f7f0e839ce8ce7ed1a6ad496ad54e74e740f74 Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 18 Nov 2026 17:05:00 +1000 Subject: [PATCH 09/16] tools: check commit message prose Check each new commit for wrapped text, short paragraphs and a blank line after the subject. Reject markdown headings and references to a PR, its review or another commit by relative position. Co-authored-by: Cursor --- Makefile | 6 ++- tools/check-commit-msgs.py | 90 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) create mode 100755 tools/check-commit-msgs.py diff --git a/Makefile b/Makefile index 07743bf82a33..ff1c8d967ac8 100644 --- a/Makefile +++ b/Makefile @@ -719,8 +719,12 @@ check-switch-default: check-comments: @tools/check-comments.py $(BASE_REF) +# The message of each commit since BASE_REF. +check-commit-msgs: + @tools/check-commit-msgs.py $(BASE_REF) + # This should NOT compile things! -check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments +check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments check-commit-msgs full-check: check check-source diff --git a/tools/check-commit-msgs.py b/tools/check-commit-msgs.py new file mode 100755 index 000000000000..bcebd541511b --- /dev/null +++ b/tools/check-commit-msgs.py @@ -0,0 +1,90 @@ +#!/usr/bin/env python3 +"""Flag commit messages in BASE..HEAD which are hard to read, or go stale. + +Once a commit lands, its message is all that explains it. The pull request +and its review are not part of the history, and the commit before it is +not the same one after a rebase or a cherry-pick. So the message has to +stand on its own, as plain wrapped text in paragraphs short enough to +follow. + +Indented lines are quoted output, not prose, so logs and backtraces can be +any width and length. Links and trailers are left alone too. +""" +import re +import subprocess +import sys + +MAX_COLUMNS = 80 +MAX_PARAGRAPH = 10 + +TRAILER = re.compile(r'(Changelog-[A-Za-z]+|Signed-off-by|Co-authored-by|Fixes|Closes' + r'|Reported-by|Suggested-by|Reviewed-by|Tested-by|Acked-by' + r'|Assisted-by|Cc|Link)\s*:|Changelog-None|\(cherry picked from', re.I) +HEADER = re.compile(r'#{1,6} \S') +UNSEEN = re.compile(r'\bthis (pr|mr|pull request)\b|\breview(er)? (comments?|feedback)\b' + r'|\bper review\b|\bas (requested|discussed)\b', re.I) +BY_POSITION = re.compile(r'\b(previous|last|earlier|prior|preceding|parent) (commit|patch)(es|s)?\b', re.I) + + +def is_prose(line): + return bool(line.strip() + and not line.startswith((' ', '\t', '>')) + and not TRAILER.match(line)) + + +def problems(message): + lines = message.rstrip('\n').split('\n') + if len(lines) > 1 and lines[1].strip(): + yield 'needs a blank line after the subject' + + paragraph = longest = 0 + wide = header = unseen = by_position = False + for line in lines[1:]: + if not is_prose(line): + paragraph = 0 + continue + paragraph += 1 + longest = max(longest, paragraph) + if len(line) > MAX_COLUMNS and '://' not in line and ' ' in line.strip(): + wide = True + header = header or bool(HEADER.match(line)) + unseen = unseen or bool(UNSEEN.search(line)) + by_position = by_position or bool(BY_POSITION.search(line)) + + if wide: + yield (f'has text wider than {MAX_COLUMNS} columns:' + ' wrap what you wrote, and indent any output you quote') + if longest > MAX_PARAGRAPH: + yield (f'has a paragraph of {longest} lines (limit {MAX_PARAGRAPH}):' + ' break it up, and indent any output you quote') + if header: + yield 'has markdown headers: commit messages are plain text' + if unseen: + yield 'refers to a pull request or review which the reader cannot see' + if by_position: + yield ('refers to an earlier commit by its position:' + ' say what the code does now, so this commit stands on its own') + + +def main(): + base = sys.argv[1] if len(sys.argv) > 1 else 'master' + log = subprocess.run(['git', 'log', '--reverse', '--no-merges', + '--format=%x01%h %s%x00%B', f'{base}..HEAD'], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + if log.returncode != 0: + print(f"check-commit-msgs: cannot list commits from '{base}':" + " set BASE_REF to the branch this work is based on", + file=sys.stderr) + sys.exit(1) + + failed = False + for commit in log.stdout.split('\x01')[1:]: + name, message = commit.split('\x00') + for problem in problems(message): + print(f'{name}: message {problem}') + failed = True + sys.exit(1 if failed else 0) + + +if __name__ == '__main__': + main() From fc5ce382768e4251762cf03095b887509a45c876 Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Thu, 19 Nov 2026 08:56:32 +1000 Subject: [PATCH 10/16] tools: reject unused added functions Reject a new non-static function when no tracked C file calls it. Calls from tests and later commits in the branch count; generated wire helpers are exempt. Co-authored-by: Cursor --- Makefile | 5 +- tools/check-commits.sh | 3 + tools/check-unused-functions.py | 108 ++++++++++++++++++++++++++++++++ 3 files changed, 115 insertions(+), 1 deletion(-) create mode 100755 tools/check-unused-functions.py diff --git a/Makefile b/Makefile index ff1c8d967ac8..5ae5c6595fb8 100644 --- a/Makefile +++ b/Makefile @@ -719,12 +719,15 @@ check-switch-default: check-comments: @tools/check-comments.py $(BASE_REF) +check-unused-functions: + @tools/check-unused-functions.py $(BASE_REF) + # The message of each commit since BASE_REF. check-commit-msgs: @tools/check-commit-msgs.py $(BASE_REF) # This should NOT compile things! -check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments check-commit-msgs +check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments check-unused-functions check-commit-msgs full-check: check check-source diff --git a/tools/check-commits.sh b/tools/check-commits.sh index d0c3dbe2e172..d2f0b4e7f153 100755 --- a/tools/check-commits.sh +++ b/tools/check-commits.sh @@ -146,6 +146,9 @@ main() { mkdir -p "$logdir" || exit 1 orig=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD) + # A check may need to see what the rest of the branch does with a commit. + CHECK_COMMITS_TIP=$(git rev-parse HEAD) || exit 1 + export CHECK_COMMITS_TIP trap restore_head EXIT trap 'exit 130' INT TERM diff --git a/tools/check-unused-functions.py b/tools/check-unused-functions.py new file mode 100755 index 000000000000..a870d1b70b52 --- /dev/null +++ b/tools/check-unused-functions.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Flag an added function which nothing calls. + +Unused code is buggy code: nothing runs it, so nothing shows that it +works. The compiler says so for a static function; this is the same check +for one which is not static. + +Only functions defined on added lines are checked (see +tools/added-lines.sh). A caller in a unit test counts. towire_ and +fromwire_ functions are left alone: generated code calls them, and it is +not tracked. + +A commit in the middle of a branch may add a function for a later commit +to call. tools/check-commits.sh sets CHECK_COMMITS_TIP to the last commit +of the branch, and callers are then looked for there. +""" +import os +import re +import subprocess +import sys + +PATHSPECS = ['*.c', ':(exclude)ccan/', ':(exclude)contrib/', ':(exclude)external/', + ':(exclude)tests/', ':(exclude)*/test/*'] + +# Comments, strings and character constants: none of them hold code. +NOT_CODE = re.compile(r'''//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*' ''', re.S | re.X) +# A return type and a name at the left margin: a definition or a prototype. +# The name may be on the next line, as it often is for pointer returns. +DECLARATION = re.compile(r'^(?!static\b)(?:\w+[ \t*]+)+(?:\n)?(\w+)\(', re.M) +BODY_OR_END = re.compile(r'[{;]') +GENERATED_CALLERS = ('towire_', 'fromwire_', 'printwire_') + + +def code_only(text): + """Blank out whatever is not code, keeping every line where it was.""" + return NOT_CODE.sub(lambda m: re.sub(r'[^\n]', ' ', m.group()), text) + + +def definitions(code): + """(line, name) of each function which is defined and not static.""" + for declaration in DECLARATION.finditer(code): + body = BODY_OR_END.search(code, declaration.end()) + if body and body.group() == '{': + yield code.count('\n', 0, declaration.start(1)) + 1, declaration.group(1) + + +def is_use(line, name): + """Does this line of code name the function, other than to declare it?""" + if not re.search(rf'\b{name}\b', line): + return False + if re.match(rf'\s*(?!return\b)[\w*][\w\s*]*\b{name}\(', line): + return False + # A pointer-returning definition may put the name at the left margin, + # with its return type on the line before. + return not re.match(rf'{name}\(', line) + + +def used(names): + """Those of the names which some tracked C file uses.""" + tip = os.environ.get('CHECK_COMMITS_TIP') + command = ['git', 'grep', '-h', '-w', '-I'] + for name in names: + command += ['-e', name] + # Files which git does not know yet are part of the working tree too. + grep = subprocess.run(command + ([tip] if tip else ['--untracked']) + ['--', '*.c', '*.h'], + stdout=subprocess.PIPE, text=True, errors='replace') + found = set() + for line in grep.stdout.splitlines(): + # A block comment which this line only starts, or is in the middle of. + line = re.sub(r'/\*.*', '', code_only(line)) + if line.lstrip().startswith('*'): + continue + found.update(name for name in names if is_use(line, name)) + return found + + +def main(): + base = sys.argv[1] if len(sys.argv) > 1 else 'master' + helper = os.path.join(os.path.dirname(sys.argv[0]), 'added-lines.sh') + lines = subprocess.run([helper, base] + PATHSPECS, + check=True, stdout=subprocess.PIPE, text=True) + added = {} + for entry in lines.stdout.splitlines(): + path, line = entry.rsplit(':', 1) + added.setdefault(path, set()).add(int(line)) + + new = {} + for path in sorted(added): + with open(path, errors='replace') as f: + code = code_only(f.read()) + for line, name in definitions(code): + if (line in added[path] and name != 'main' + and not name.startswith(GENERATED_CALLERS)): + new.setdefault(name, []).append((path, line)) + if not new: + sys.exit(0) + + unused = sorted((path, line, name) + for name in set(new) - used(set(new)) + for path, line in new[name]) + for path, line, name in unused: + print(f'{path}:{line}: {name}() has no caller:' + ' unused code is buggy code, so leave it out until something needs it') + sys.exit(1 if unused else 0) + + +if __name__ == '__main__': + main() From 49afa80bcc7188b231e92ef44187e729f5cf9b1d Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Thu, 19 Nov 2026 08:56:32 +1000 Subject: [PATCH 11/16] tools: require NULL parents for take() An object allocated only to be handed over with take() should have no other owner. Reject added take() calls which allocate from tmpctx or pass a non-NULL parent to tal or towire helpers. Co-authored-by: Cursor --- Makefile | 5 +++- tools/check-take-parent.py | 56 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100755 tools/check-take-parent.py diff --git a/Makefile b/Makefile index 5ae5c6595fb8..49e88d22f8b9 100644 --- a/Makefile +++ b/Makefile @@ -722,12 +722,15 @@ check-comments: check-unused-functions: @tools/check-unused-functions.py $(BASE_REF) +check-take-parent: + @tools/check-take-parent.py $(BASE_REF) + # The message of each commit since BASE_REF. check-commit-msgs: @tools/check-commit-msgs.py $(BASE_REF) # This should NOT compile things! -check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments check-unused-functions check-commit-msgs +check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments check-unused-functions check-take-parent check-commit-msgs full-check: check check-source diff --git a/tools/check-take-parent.py b/tools/check-take-parent.py new file mode 100755 index 000000000000..7698ecad4161 --- /dev/null +++ b/tools/check-take-parent.py @@ -0,0 +1,56 @@ +#!/usr/bin/env python3 +"""Flag take() of something which was allocated off a parent. + +take() gives its argument to the function being called. Something +allocated only to be given away should be allocated off NULL, so it is +clear that nothing else owns it: + + subd_send_msg(sd, take(towire_foo(NULL, ...))); + +Only added lines are checked (see tools/added-lines.sh). The allocations +recognised are the ones which name their parent first: anything given +tmpctx, and the towire_ and tal functions. +""" +import os +import re +import subprocess +import sys + +PATHSPECS = ['*.c', '*.h', ':(exclude)ccan/', ':(exclude)contrib/', ':(exclude)external/'] + +# Comments, strings and character constants: none of them hold code. +NOT_CODE = re.compile(r'''//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*' ''', re.S | re.X) +TAKE = re.compile(r'\btake\(\s*(?:\w+\(\s*(tmpctx)\b|(?:towire_\w+|tal\w*)\(\s*(?!NULL\b)(\w+))') + + +def code_only(text): + """Blank out whatever is not code, keeping every line where it was.""" + return NOT_CODE.sub(lambda m: re.sub(r'[^\n]', ' ', m.group()), text) + + +def main(): + base = sys.argv[1] if len(sys.argv) > 1 else 'master' + helper = os.path.join(os.path.dirname(sys.argv[0]), 'added-lines.sh') + lines = subprocess.run([helper, base] + PATHSPECS, + check=True, stdout=subprocess.PIPE, text=True) + added = {} + for entry in lines.stdout.splitlines(): + path, line = entry.rsplit(':', 1) + added.setdefault(path, set()).add(int(line)) + + failed = False + for path in sorted(added): + with open(path, errors='replace') as f: + code = code_only(f.read()) + for take in TAKE.finditer(code): + line = code.count('\n', 0, take.start()) + 1 + if line in added[path]: + parent = take.group(1) or take.group(2) + print(f'{path}:{line}: take() of something allocated off {parent}:' + ' allocate it off NULL, since take() gives it away') + failed = True + sys.exit(1 if failed else 0) + + +if __name__ == '__main__': + main() From 3d9ba60ac4f31ebbcac61d3fbb0edc64874a8cd7 Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Thu, 19 Nov 2026 08:56:32 +1000 Subject: [PATCH 12/16] tools: require a subsystem in commit subjects Require commit subjects to use the "subsystem: intent" form from the style guide, where a subsystem is a single word like "wallet" or a comma-separated list of them. Cap subjects at 80 columns. Releases and reverts keep their own forms. A conventional-commit type like "fix:" or "chore:" names the kind of change, not the part of the tree it changes, so it is rejected: the style guide says not to annotate with "Chore" etc. A fixup! subject is rejected outright: maintainers rebase a branch as it is, so an unfolded fixup would land on master for someone else to clean up. Co-authored-by: Cursor --- tools/check-commit-msgs.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/tools/check-commit-msgs.py b/tools/check-commit-msgs.py index bcebd541511b..7466ed93fc0c 100755 --- a/tools/check-commit-msgs.py +++ b/tools/check-commit-msgs.py @@ -5,7 +5,9 @@ and its review are not part of the history, and the commit before it is not the same one after a rebase or a cherry-pick. So the message has to stand on its own, as plain wrapped text in paragraphs short enough to -follow. +follow. Its subject names the part of the tree it changes, as in +"lightningd: fix a crash on restart", which is what a reader scans for in +the log. Indented lines are quoted output, not prose, so logs and backtraces can be any width and length. Links and trailers are left alone too. @@ -16,11 +18,22 @@ MAX_COLUMNS = 80 MAX_PARAGRAPH = 10 +MAX_SUBJECT = 80 TRAILER = re.compile(r'(Changelog-[A-Za-z]+|Signed-off-by|Co-authored-by|Fixes|Closes' r'|Reported-by|Suggested-by|Reviewed-by|Tested-by|Acked-by' r'|Assisted-by|Cc|Link)\s*:|Changelog-None|\(cherry picked from', re.I) HEADER = re.compile(r'#{1,6} \S') +# "subsystem: intent", where a subsystem is one word, as in "wallet:" or +# "connectd, lightningd:". Prose before the colon is not a subsystem. A +# release commit and git's own revert subjects are left alone. +SUBJECT = re.compile(r'[\w./-]+(, [\w./-]+)*: \S|v\d+\.\d+\S*$|Revert "') +# Maintainers rebase a branch as it is: nothing folds a fixup for you. +UNFOLDED = re.compile(r'(fixup|squash|amend)! ') +# "fix:" names the kind of change, not the part of the tree it changes. +# The style guide: don't annotate with "Chore" etc. +CHANGE_TYPE = re.compile(r'(feat|fix|chore|refactor|perf|style)(\([^)]*\))?!?: ', + re.I) UNSEEN = re.compile(r'\bthis (pr|mr|pull request)\b|\breview(er)? (comments?|feedback)\b' r'|\bper review\b|\bas (requested|discussed)\b', re.I) BY_POSITION = re.compile(r'\b(previous|last|earlier|prior|preceding|parent) (commit|patch)(es|s)?\b', re.I) @@ -34,6 +47,17 @@ def is_prose(line): def problems(message): lines = message.rstrip('\n').split('\n') + if UNFOLDED.match(lines[0]): + yield ('is a fixup! commit: fold it into its target' + ' before the branch is merged') + elif CHANGE_TYPE.match(lines[0]): + yield ('has a subject naming the kind of change:' + ' name the subsystem it changes instead') + elif not SUBJECT.match(lines[0]): + yield ('needs a subject of the form "subsystem: intent",' + ' naming the daemon or directory it changes') + if len(lines[0]) > MAX_SUBJECT: + yield f'has a subject wider than {MAX_SUBJECT} columns: shorten it' if len(lines) > 1 and lines[1].strip(): yield 'needs a blank line after the subject' From 20e81e8fe628edb9e3076398699465d273b84c74 Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Thu, 19 Nov 2026 08:56:32 +1000 Subject: [PATCH 13/16] pre-commit: remove the stale commitlint hook The prefix allowlist rejects valid subsystems and requires constant maintenance. check-source now checks subject shape without an allowlist. Co-authored-by: Cursor --- .pre-commit-config.yaml | 6 ----- commitlint.config.js | 56 ----------------------------------------- 2 files changed, 62 deletions(-) delete mode 100644 commitlint.config.js diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 65e0f58bec8d..17d1ae099d77 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -65,12 +65,6 @@ repos: exclude: ccan|contrib|tests/fuzz/corpora stages: [ manual ] -- repo: https://github.com/alessandrojcm/commitlint-pre-commit-hook - rev: v9.23.0 - hooks: - - id: commitlint - stages: [ commit-msg ] - - repo: local hooks: # Reimplementation of `make check-amount-access` for pygrep. diff --git a/commitlint.config.js b/commitlint.config.js deleted file mode 100644 index f156abd38cc5..000000000000 --- a/commitlint.config.js +++ /dev/null @@ -1,56 +0,0 @@ -module.exports = { - - plugins: [ - { - rules: { - 'core-lightning': ({ type }) => { - // Allow standard Core Lightning types - const standardTypes = [ - // Daemons - 'channeld', 'closingd', 'connectd', 'gossipd', 'hsmd', 'lightningd', 'onchaind', - 'openingd', - // Related - 'bitcoin', 'cli', 'cln-grpc', 'cln-rpc', 'db', 'wallet', 'wire', - // Others - 'ci', 'common', 'contrib', 'devtools', 'docs', 'docker', 'github', 'global', - 'meta', 'nit', 'nix', 'release', 'script', 'tests', - ]; - - // Extensions - const extensions = ['plugin-', 'pyln-', 'tool-'] - if (type) { - for (const prefix of extensions) { - if (type.startsWith(prefix)) { - return [true]; - } - } - } - - // Otherwise, must be a standard type - if (standardTypes.includes(type)) { - return [true]; - } - - return [ - false, - `Type must be one of [${standardTypes.join(', ')}] or match patterns [${extensions.join(', ')}]` - ]; - }, - }, - }, - ], - - rules: { - // Disable the default type-enum rule since we're using custom validation - 'type-enum': [0], - - // Enable our custom rule - 'core-lightning': [2, 'always'], - - // Keep other standard rules - 'type-case': [2, 'always', 'lower-case'], - 'type-empty': [2, 'never'], - 'subject-empty': [2, 'never'], - 'subject-case': [2, 'never', ['upper-case']], - }, -}; From 86e80f7772fec147ced17c0cacc490b5e90fa635 Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 25 Nov 2026 14:19:08 +1000 Subject: [PATCH 14/16] tools: require tab indentation in C code Flag an added line which starts a new statement -- one after `;`, `{`, `}` or a label -- and is indented with spaces, or puts spaces before a tab. Spaces still align a continuation under the line before. Over the last 300 commits of merged code this fires twice, both on lines tabs would have improved. Co-authored-by: Cursor --- Makefile | 5 ++- tools/check-tab-indent.py | 71 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100755 tools/check-tab-indent.py diff --git a/Makefile b/Makefile index 49e88d22f8b9..04ebda12d7d5 100644 --- a/Makefile +++ b/Makefile @@ -725,12 +725,15 @@ check-unused-functions: check-take-parent: @tools/check-take-parent.py $(BASE_REF) +check-tab-indent: + @tools/check-tab-indent.py $(BASE_REF) + # The message of each commit since BASE_REF. check-commit-msgs: @tools/check-commit-msgs.py $(BASE_REF) # This should NOT compile things! -check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments check-unused-functions check-take-parent check-commit-msgs +check-source: check-makefile check-whitespace check-spelling check-python-flake8 check-includes check-shellcheck check-setup_locale check-tmpctx check-discouraged-functions check-amount-access check-bad-sprintf check-wire-format check-source-bolt check-security check-msggen-grpc check-grpc-breaking check-switch-default check-comments check-unused-functions check-take-parent check-tab-indent check-commit-msgs full-check: check check-source diff --git a/tools/check-tab-indent.py b/tools/check-tab-indent.py new file mode 100755 index 000000000000..1bf175f5101b --- /dev/null +++ b/tools/check-tab-indent.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +"""Flag added C lines which are indented with spaces. + +The C code is indented with TAB characters (see .editorconfig). Spaces +only align a continuation, under the open paren of the line before: + + static void subtract_received_htlcs(const struct channel *channel, + struct amount_msat *amount) + +So a line which starts a new statement -- one after a `;`, `{`, `}` or a +label -- must start with a tab. Only added lines are checked (see +tools/added-lines.sh). +""" +import os +import re +import subprocess +import sys + +PATHSPECS = ['*.c', '*.h', ':(exclude)ccan/', ':(exclude)contrib/'] + +# Comments, strings and character constants: none of them hold code. +NOT_CODE = re.compile(r'''//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*' ''', re.S | re.X) + +# After one of these a new statement starts: nothing to align under. +BOUNDARY = re.compile(r'[;:{}]$') + + +def code_only(text): + """Blank out whatever is not code, keeping every line where it was.""" + return NOT_CODE.sub(lambda m: re.sub(r'[^\n]', ' ', m.group()), text) + + +def problems(code): + """(line, complaint) for each line which is indented with spaces.""" + previous = '' + for number, line in enumerate(code.split('\n'), 1): + stripped = line.rstrip() + if not stripped or stripped.lstrip().startswith('#'): + continue + indent = line[:len(line) - len(line.lstrip())] + if ' \t' in indent: + yield number, 'is indented with spaces before a tab: use tabs' + elif (indent.startswith(' ') and not previous.endswith('\\') + and BOUNDARY.search(previous)): + yield number, 'is indented with spaces: use tabs' + previous = stripped + + +def main(): + base = sys.argv[1] if len(sys.argv) > 1 else 'master' + helper = os.path.join(os.path.dirname(sys.argv[0]), 'added-lines.sh') + lines = subprocess.run([helper, base] + PATHSPECS, + check=True, stdout=subprocess.PIPE, text=True) + added = {} + for entry in lines.stdout.splitlines(): + path, line = entry.rsplit(':', 1) + added.setdefault(path, set()).add(int(line)) + + failed = False + for path in sorted(added): + with open(path, errors='replace') as f: + code = code_only(f.read()) + for line, complaint in problems(code): + if line in added[path]: + print(f'{path}:{line}: line {complaint}') + failed = True + sys.exit(1 if failed else 0) + + +if __name__ == '__main__': + main() From 712cb9f8c7e0d72e5e51eefeba8569a79c15e81b Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 25 Nov 2026 14:19:09 +1000 Subject: [PATCH 15/16] tools: reject take() in wire call arguments The generated marshalling code does not support take(): it never frees what it is given, so the argument leaks. take() wrapping the wire call itself is the documented pattern, and still passes. Co-authored-by: Cursor --- tools/check-take-parent.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tools/check-take-parent.py b/tools/check-take-parent.py index 7698ecad4161..698bdbba535f 100755 --- a/tools/check-take-parent.py +++ b/tools/check-take-parent.py @@ -7,6 +7,10 @@ subd_send_msg(sd, take(towire_foo(NULL, ...))); +The generated marshalling code does not support take() at all: a take() +anywhere in the arguments of a towire_ or fromwire_ call leaks what it +was given. + Only added lines are checked (see tools/added-lines.sh). The allocations recognised are the ones which name their parent first: anything given tmpctx, and the towire_ and tal functions. @@ -21,6 +25,7 @@ # Comments, strings and character constants: none of them hold code. NOT_CODE = re.compile(r'''//[^\n]*|/\*.*?\*/|"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*' ''', re.S | re.X) TAKE = re.compile(r'\btake\(\s*(?:\w+\(\s*(tmpctx)\b|(?:towire_\w+|tal\w*)\(\s*(?!NULL\b)(\w+))') +WIRE_CALL = re.compile(r'\b(?:towire|fromwire)_\w+\(') def code_only(text): @@ -28,6 +33,22 @@ def code_only(text): return NOT_CODE.sub(lambda m: re.sub(r'[^\n]', ' ', m.group()), text) +def wire_takes(code): + """Offset of each take() inside the arguments of a wire call.""" + for call in WIRE_CALL.finditer(code): + depth = 1 + for i in range(call.end(), len(code)): + if code[i] == '(': + depth += 1 + elif code[i] == ')': + depth -= 1 + if depth == 0: + break + take = re.compile(r'\btake\(').search(code, call.end(), i) + if take: + yield take.start() + + def main(): base = sys.argv[1] if len(sys.argv) > 1 else 'master' helper = os.path.join(os.path.dirname(sys.argv[0]), 'added-lines.sh') @@ -49,6 +70,12 @@ def main(): print(f'{path}:{line}: take() of something allocated off {parent}:' ' allocate it off NULL, since take() gives it away') failed = True + for offset in wire_takes(code): + line = code.count('\n', 0, offset) + 1 + if line in added[path]: + print(f'{path}:{line}: take() in the arguments of a wire call:' + ' the generated marshalling never frees it, so it leaks') + failed = True sys.exit(1 if failed else 0) From d758e75875da8698e0654f551a3cf0aa9be7741b Mon Sep 17 00:00:00 2001 From: Sangbida Chaudhuri Date: Wed, 25 Nov 2026 14:19:09 +1000 Subject: [PATCH 16/16] tools: test the source checkers Show what each checker accepts and rejects with named examples, so a contributor reads the spec instead of the regexes. Known gaps are xfail(strict=True): fixing one fails the run until its marker is removed, so the spec cannot go stale. Co-authored-by: Cursor --- tools/tests/test_checks.py | 394 +++++++++++++++++++++++++++++++++++++ 1 file changed, 394 insertions(+) create mode 100644 tools/tests/test_checks.py diff --git a/tools/tests/test_checks.py b/tools/tests/test_checks.py new file mode 100644 index 000000000000..904a3b72bbe8 --- /dev/null +++ b/tools/tests/test_checks.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +"""The spec for the tools/check-*.py source checkers. + +Each case here shows a contributor (or their agent) exactly what the +checkers accept and reject, so nobody has to guess from the regexes. + +Plain tests document behaviour the checkers promise today. Tests marked +xfail(strict=True) document known gaps: behaviour we want but do not have +yet. When a gap is fixed, its xfail starts passing and pytest fails the +run, so the marker must be removed with the fix. + +Run with: uv run pytest tools/tests/test_checks.py +""" +import importlib.util +import sys +from pathlib import Path + +import pytest + +TOOLS = Path(__file__).resolve().parent.parent + + +def load(name): + """Import a hyphenated tools/ script as a module.""" + modname = name.replace('-', '_') + spec = importlib.util.spec_from_file_location(modname, TOOLS / f'{name}.py') + module = importlib.util.module_from_spec(spec) + sys.modules[modname] = module + spec.loader.exec_module(module) + return module + + +check_comments = load('check-comments') +check_commit_msgs = load('check-commit-msgs') +check_switch_default = load('check-switch-default') +check_tab_indent = load('check-tab-indent') +check_take_parent = load('check-take-parent') +check_unused_functions = load('check-unused-functions') + + +# ---------------------------------------------------------------------- +# check-comments: added comments must describe the code, not the change. +# ---------------------------------------------------------------------- + +def comment_complaints(text, path='x.c', added=None): + """Complaints for `text`; by default every line counts as added.""" + if added is None: + added = set(range(1, text.count('\n') + 2)) + return [complaint for _, complaint in + check_comments.problems(path, text, added)] + + +GOOD_COMMENTS = [ + pytest.param('/* Send the message to the peer. */\n', + id='describes-the-code'), + pytest.param('/* We sign this commitment and revoke the old one. */\n', + id='commitment-is-not-a-git-commit'), + pytest.param('/* BOLT #2:\n' + ' * quoted spec text\n' * 10 + ' */\n', + id='bolt-quote-may-be-long'), + pytest.param('/*~ This walkthrough comment teaches the reader,\n' + + ' * and tutorial prose takes room.\n' * 10 + ' */\n', + id='tutorial-comment-may-be-long'), + pytest.param('\t/* one\n\t * two\n\t * three\n\t * four */\n', + id='indented-four-lines-is-at-the-limit'), +] + +BAD_COMMENTS = [ + pytest.param('/* This fix handles the crash. */\n', + id='narrates-the-change'), + pytest.param('/* The old implementation used a list. */\n', + id='describes-removed-code'), + pytest.param('/* See PR #9748 for details. */\n', + id='cites-a-pull-request'), + pytest.param('/* Added per review feedback. */\n', + id='cites-a-review'), + pytest.param('/* See channeld/channeld.c:123 for the caller. */\n', + id='points-at-a-line-number'), + pytest.param('/* one\n' + ' * filler\n' * 7 + ' */\n', + id='nine-lines-at-margin-is-over-the-limit'), + pytest.param('\t/* one\n\t * two\n\t * three\n\t * four\n\t * five */\n', + id='five-indented-lines-is-over-the-limit'), + pytest.param('/* kept per review; BOLT semantics unchanged */\n', + id='the-word-bolt-is-not-an-exemption'), +] + + +@pytest.mark.parametrize('text', GOOD_COMMENTS) +def test_good_comments(text): + assert comment_complaints(text) == [] + + +@pytest.mark.parametrize('text', BAD_COMMENTS) +def test_bad_comments(text): + assert comment_complaints(text) != [] + + +@pytest.mark.xfail(strict=True, reason='"this commit tx" is a commitment' + ' transaction, not a git commit') +def test_commit_tx_is_not_a_git_commit(): + assert comment_complaints('/* Sign this commit tx. */\n') == [] + + +@pytest.mark.xfail(strict=True, reason='the style guide endorses FIXME:' + ' refactor notes') +def test_fixme_refactor_is_allowed(): + assert comment_complaints('/* FIXME: refactor into common/ */\n') == [] + + +@pytest.mark.xfail(strict=True, reason='"as requested by the peer" is' + ' protocol prose, not review prose') +def test_peer_requests_are_not_review_requests(): + assert comment_complaints( + '/* As requested by the peer, forget the channel. */\n') == [] + + +@pytest.mark.xfail(strict=True, reason='editing one line of an existing' + ' long comment should not fail the whole comment') +def test_partial_edit_of_long_comment(): + text = '/* one\n' + ' * filler\n' * 10 + ' */\n' + assert comment_complaints(text, added={5}) == [] + + +# ---------------------------------------------------------------------- +# check-commit-msgs: a message must stand on its own after the PR is gone. +# ---------------------------------------------------------------------- + +def msg_complaints(message): + return list(check_commit_msgs.problems(message)) + + +GOOD_MESSAGES = [ + pytest.param('wallet: fix incorrect channel_htlcs id migration\n' + '\nThe migration wrote ids from the wrong table.\n', + id='subsystem-intent-with-body'), + pytest.param('connectd, lightningd: ignore unknown channel errors\n' + '\nBoth daemons see them.\n', + id='two-subsystems-are-fine'), + pytest.param('Revert "wallet: fix incorrect migration"\n' + '\nIt broke replays.\n', + id='reverts-keep-gits-own-subject'), + pytest.param('lightningd: quote the crash\n\nThe log said:\n\n' + ' ' + 'x' * 100 + '\n', + id='indented-quoted-output-may-be-wide'), + pytest.param('doc: link the spec\n\n' + 'https://github.com/lightning/bolts/blob/master/' + '02-peer-protocol.md#channel-establishment-v2\n', + id='urls-may-be-wide'), + pytest.param('wallet: fix migration\n\nWhy.\n\n' + 'Changelog-Fixed: wallet: ' + 'x' * 70 + '\n', + id='trailers-may-be-wide'), + pytest.param('build: use -Werror on debug builds\n\nWhy.\n', + id='build-is-a-real-subsystem'), +] + +BAD_MESSAGES = [ + pytest.param('Fix the crash\n\nBody.\n', + id='no-subsystem-prefix'), + pytest.param('wallet: fix migration\nBody with no blank line.\n', + id='no-blank-line-after-subject'), + pytest.param('doc: update\n\n# Overview\n\nText.\n', + id='markdown-headers'), + pytest.param('wallet: fix migration\n\n' + 'word ' * 20 + '\n', + id='prose-wider-than-80-columns'), + pytest.param('wallet: fix migration\n\n' + 'Changed as discussed in the review.\n', + id='refers-to-the-review'), + pytest.param('wallet: fix migration\n\n' + 'The previous commit added the table.\n', + id='refers-to-a-commit-by-position'), + pytest.param('wallet: fix migration\n\n' + 'A line of prose.\n' * 11, + id='paragraph-longer-than-ten-lines'), + pytest.param('fixup! wallet: fix incorrect migration\n', + id='unfolded-fixups-do-not-merge'), + pytest.param('squash! wallet: fix incorrect migration\n', + id='unfolded-squashes-do-not-merge'), + pytest.param('fix: release txprepare reservations on send failure\n', + id='fix-is-a-kind-of-change-not-a-subsystem'), + pytest.param('chore(deps): bump pyln-client\n', + id='conventional-commit-scopes-are-not-subsystems'), + pytest.param('Feat: enhance JUnit XML reporting\n', + id='change-types-are-rejected-in-any-case'), +] + + +@pytest.mark.parametrize('message', GOOD_MESSAGES) +def test_good_messages(message): + assert msg_complaints(message) == [] + + +@pytest.mark.parametrize('message', BAD_MESSAGES) +def test_bad_messages(message): + assert msg_complaints(message) != [] + + +def test_prose_subject_is_not_a_subsystem(): + assert msg_complaints('I Fixed This: lol\n\nBody.\n') != [] + + +def test_subject_length_is_capped(): + assert msg_complaints('wallet: ' + 'long ' * 20 + '\n\nBody.\n') != [] + + +@pytest.mark.xfail(strict=True, reason='"the last commit tx" is a commitment' + ' transaction, not a git commit') +def test_commit_tx_in_message_is_not_by_position(): + assert msg_complaints('channeld: resend the last commit tx\n\n' + 'We retransmit the last commit tx we signed.\n') == [] + + +# ---------------------------------------------------------------------- +# check-switch-default: a switch over an enum lists every case. +# ---------------------------------------------------------------------- + +def switch_hits(code, names=frozenset()): + return list(check_switch_default.enum_defaults( + check_switch_default.code_only(code), names)) + + +def test_default_in_enum_switch_is_rejected(): + code = ('void f(enum color c)\n{\n' + '\tswitch (c) {\n' + '\tcase COLOR_RED:\n\t\tbreak;\n' + '\tdefault:\n\t\tbreak;\n' + '\t}\n}\n') + assert switch_hits(code, {'COLOR_RED', 'COLOR_BLUE'}) != [] + + +def test_wire_cases_count_as_enum_without_harvest(): + code = ('void f(int t)\n{\n' + '\tswitch (t) {\n' + '\tcase WIRE_PING:\n\t\tbreak;\n' + '\tdefault:\n\t\tbreak;\n' + '\t}\n}\n') + assert switch_hits(code) != [] + + +def test_errno_switch_keeps_its_default(): + code = ('void f(int e)\n{\n' + '\tswitch (e) {\n' + '\tcase EINTR:\n\t\tbreak;\n' + '\tdefault:\n\t\tbreak;\n' + '\t}\n}\n') + assert switch_hits(code, {'COLOR_RED'}) == [] + + +def test_exhaustive_enum_switch_passes(): + code = ('void f(enum color c)\n{\n' + '\tswitch (c) {\n' + '\tcase COLOR_RED:\n\tcase COLOR_BLUE:\n\t\tbreak;\n' + '\t}\n}\n') + assert switch_hits(code, {'COLOR_RED', 'COLOR_BLUE'}) == [] + + +def test_inner_integer_switch_keeps_its_default(): + code = ('void f(enum color c, int x)\n{\n' + '\tswitch (c) {\n' + '\tcase COLOR_RED: {\n' + '\t\tswitch (x) {\n' + '\t\tcase 3:\n\t\t\tbreak;\n' + '\t\tdefault:\n\t\t\tbreak;\n' + '\t\t}\n' + '\t\tbreak;\n' + '\t}\n' + '\t}\n}\n') + assert switch_hits(code, {'COLOR_RED'}) == [] + + +# ---------------------------------------------------------------------- +# check-take-parent: take() gives its argument away, so allocate off NULL. +# ---------------------------------------------------------------------- + +def take_hits(code): + return [m.group(1) or m.group(2) for m in check_take_parent.TAKE.finditer( + check_take_parent.code_only(code))] + + +def test_take_of_null_allocation_passes(): + assert take_hits('send(p, take(towire_foo(NULL, x)));\n') == [] + + +def test_take_of_tmpctx_allocation_is_rejected(): + assert take_hits('send(p, take(towire_foo(tmpctx, x)));\n') == ['tmpctx'] + + +def test_take_of_tal_with_parent_is_rejected(): + assert take_hits('send(p, take(tal_dup(peer, u8, m)));\n') == ['peer'] + + +@pytest.mark.xfail(strict=True, reason='the two-line form from the style' + ' guide is not caught yet') +def test_take_of_variable_allocated_off_tmpctx(): + code = 'msg = towire_foo(tmpctx, x);\nsend(p, take(msg));\n' + assert take_hits(code) != [] + + +def wire_take_hits(code): + return list(check_take_parent.wire_takes( + check_take_parent.code_only(code))) + + +def test_take_wrapping_a_wire_call_passes(): + assert wire_take_hits('send(p, take(towire_foo(NULL, x)));\n') == [] + + +def test_take_inside_a_wire_call_is_rejected(): + assert wire_take_hits('msg = towire_foo(NULL, take(script));\n') != [] + + +def test_take_inside_a_fromwire_call_is_rejected(): + assert wire_take_hits('ok = fromwire_foo(ctx, take(msg), &x);\n') != [] + + +# ---------------------------------------------------------------------- +# check-tab-indent: C code is indented with tabs; spaces only align a +# continuation under the line before. +# ---------------------------------------------------------------------- + +def indent_hits(code): + return list(check_tab_indent.problems( + check_tab_indent.code_only(code))) + + +def test_tab_indented_body_passes(): + assert indent_hits('void f(void)\n{\n\tg();\n}\n') == [] + + +def test_space_indented_body_is_rejected(): + assert indent_hits('void f(void)\n{\n g();\n}\n') != [] + + +def test_space_before_tab_is_rejected(): + assert indent_hits('void f(void)\n{\n \tg();\n}\n') != [] + + +def test_aligned_continuation_passes(): + code = ('static void subtract(const struct channel *channel,\n' + ' struct amount_msat *amount)\n' + '{\n\tg();\n}\n') + assert indent_hits(code) == [] + + +def test_comment_interior_is_not_code(): + assert indent_hits('/* one\n * two\n */\nvoid f(void);\n') == [] + + +def test_macro_continuation_passes(): + code = '#define F(x) do { \\\n g(x); \\\n} while (0)\n' + assert indent_hits(code) == [] + + +# ---------------------------------------------------------------------- +# check-unused-functions: a new non-static function needs a caller. +# ---------------------------------------------------------------------- + +def defined(code): + return [name for _, name in check_unused_functions.definitions( + check_unused_functions.code_only(code))] + + +def test_definition_at_margin_is_found(): + assert defined('int foo(int x)\n{\n\treturn x;\n}\n') == ['foo'] + + +def test_static_definition_is_ignored(): + assert defined('static int foo(int x)\n{\n\treturn x;\n}\n') == [] + + +def test_prototype_is_not_a_definition(): + assert defined('int foo(int x);\n') == [] + + +def test_multiline_definition_is_found(): + assert 'foo' in defined('struct bar *\nfoo(int x)\n{\n\treturn NULL;\n}\n') + + +def test_indented_call_is_a_use(): + assert check_unused_functions.is_use('\tfoo(x);', 'foo') + assert check_unused_functions.is_use('\treturn foo(x);', 'foo') + assert check_unused_functions.is_use('\tif (!foo(x))', 'foo') + + +def test_declaration_at_margin_is_not_a_use(): + assert not check_unused_functions.is_use('int foo(int x);', 'foo') + assert not check_unused_functions.is_use('void foo(void)', 'foo') + + +def test_indented_prototype_is_not_a_use(): + assert not check_unused_functions.is_use('\tvoid foo(int x);', 'foo') + + +def test_declaration_after_comment_is_not_a_use(): + line = '/* Helper for foo. */ void foo(int x);' + assert not check_unused_functions.is_use( + check_unused_functions.code_only(line), 'foo')