From 3ae5c233580946075ae8bdebf63e714a86ebe01b Mon Sep 17 00:00:00 2001 From: Bruno Garcia Date: Wed, 2 Sep 2026 20:40:42 -0300 Subject: [PATCH] bech32: fix encoding a maximum length segwit address bech32_encode() allows an encoded address of up to 90 characters, as BIP-173 specifies, but wally_addr_segwit_from_bytes() encodes into a 90 byte stack buffer. When the address is exactly 90 characters long the NUL terminator is written one byte past the end of the buffer. Any 30 character hrp with a 32 byte version 0 program hits the boundary, as does any other combination whose encoded length is 90. Size the buffer for the maximum length plus the terminator, matching what the blech32 encoder already does, and add the boundary case to the bech32 test vectors so it is exercised in both directions. Found by bitcoinfuzz. --- CHANGES.md | 1 + src/bech32.c | 2 +- src/test/test_bech32.py | 5 ++++- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index d5f9bdd64..ec09666dc 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -4,6 +4,7 @@ ### Fixed - internal: De-optimize some memcpy calls on x86 to prevent leaks via extended registers. +- bech32: Fix size when encoding a maximum length (90 character) segwit address. - descriptor: Require base miniscript expressions for sh()/wsh(). - descriptor: Reject nested expressions with unconsumed trailing input. diff --git a/src/bech32.c b/src/bech32.c index bfbda6144..8600cea04 100644 --- a/src/bech32.c +++ b/src/bech32.c @@ -208,7 +208,7 @@ int wally_addr_segwit_from_bytes(const unsigned char *bytes, size_t bytes_len, const char *addr_family, uint32_t flags, char **output) { - char result[90]; + char result[90 + 1]; /* Max encoded length plus NUL */ size_t push_size; int ret; size_t witver; diff --git a/src/test/test_bech32.py b/src/test/test_bech32.py index 2aa77c408..0e51cb529 100755 --- a/src/test/test_bech32.py +++ b/src/test/test_bech32.py @@ -20,7 +20,10 @@ 'tb1pqqqqp399et2xygdj5xreqhjjvcmzhxw4aywxecjdzew6hylgvsesf3hn0c': ['tb', 1, '5120000000c4a5cad46221b2a187905e5266362b99d5e91c6ce24d165dab93e86433'], 'bc1p0xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqzk5jj0': - ['bc', 1, '512079be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'] + ['bc', 1, '512079be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'], + # Maximum length (90 character) address: 30 character hrp, 32 byte v0 program + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq6nf3d': + ['a' * 30, 0, '0020' + '00' * 32], } invalid_cases = [