Merge bitcoin/bitcoin#35989: wallet: fix crash on importdescriptors with a range ending at 2^31-1
What changed, and why it matters
This update fixes a crash in Bitcoin Core's wallet that could be triggered when importing a descriptor with a range ending at the largest 32-bit signed integer (2,147,483,647). Because the wallet stores the range end as an exclusive value in a 32-bit signed integer, that endpoint becomes 2^31 and wraps around to a negative number, causing the node to abort during keypool top-up. The patch rejects such unrepresentable ranges before they are stored, and also hardens related arithmetic to avoid similar overflows.
Apply the patch. Nodes accepting arbitrary wallet descriptor imports or using non-default -keypool values should upgrade, as the crash is reachable via RPC and can be triggered by a local wallet user or any caller with wallet RPC access.
Security signals we found
Integer overflow leading to signed truncation and node abort
Wallet RPC input validation bypass
Undefined behavior reachable through importdescriptors and keypoolrefill
Denial-of-service vector against wallet node
Regression tests added for all three overflow scenarios
Evidence from the diff
WalletDescriptor stores an exclusive range_end in int32_t. Importing a descriptor with inclusive range [INT32_MAX, INT32_MAX] produces an exclusive end of 2^31, which narrows to a negative value and aborts the node during keypool top-up. The patch adds an explicit bound check in ImportDescriptor before constructing the wallet descriptor, computes the top-up endpoint in int64_t in DescriptorScriptPubKeyMan::TopUpWithDB, and reorders CheckDescriptorRangeBounds to reject reversed ranges before computing high - low. Regression tests cover all three overflow paths.
Changed components
src/wallet/imports.cppsrc/wallet/scriptpubkeyman.cppsrc/script/descriptor.cppwallet importdescriptors RPCwallet keypoolrefill RPCInspect captured patch +78 / −5
### doc/release-notes-35989.md
@@ -0,0 +1,7 @@
+Wallet
+------
+
+- `importdescriptors` now rejects a `range` ending at 2147483647 (2^31-1), as
+ the wallet cannot store it. The same applies to imports without a `range`
+ when `-keypool` is above 2147483647, since `-keypool` is then used as the end
+ of the range. Previously such imports could crash the node.
### src/script/descriptor.cpp
@@ -57,12 +57,12 @@ util::Expected<void, std::string> CheckDescriptorRangeBounds(int64_t low, int64_
if ((high >> 31) != 0) {
return util::Unexpected<std::string>("End of range is too high");
}
- if (high >= low + 1000000) {
- return util::Unexpected<std::string>("Range is too large");
- }
if (low > high) {
return util::Unexpected<std::string>("Range specified as [begin,end] must not have begin after end");
}
+ if (high - low >= 1000000) {
+ return util::Unexpected<std::string>("Range is too large");
+ }
return {};
}
### src/wallet/imports.cpp
@@ -6,6 +6,9 @@
#include <wallet/imports.h>
#include <wallet/scan.h>
+#include <cstdint>
+#include <limits>
+
namespace wallet {
ImportResult ImportDescriptor(CWallet& wallet, const ImportDescriptorRequest& request) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
@@ -54,6 +57,11 @@ ImportResult ImportDescriptor(CWallet& wallet, const ImportDescriptorRequest& re
range_start = 0;
range_end = wallet.m_keypool_size;
}
+ // WalletDescriptor stores the range as int32_t with an exclusive end, so an
+ // end past the maximum index would be truncated to a negative range.
+ if (range_end > std::numeric_limits<int32_t>::max()) {
+ return ImportResult(WalletErrorCode::InvalidParameter, "End of range is too high", warnings);
+ }
next_index = request.next_index.value_or(range_start);
is_ranged = true;
### src/wallet/scriptpubkeyman.cpp
@@ -21,6 +21,7 @@
#include <util/time.h>
#include <util/translation.h>
+#include <limits>
#include <optional>
using common::PSBTError;
@@ -1127,8 +1128,14 @@ bool DescriptorScriptPubKeyMan::TopUpWithDB(WalletBatch& batch, unsigned int siz
target_size = m_keypool_size;
}
- // Calculate the new range_end
- int32_t new_range_end = std::max(m_wallet_descriptor.GetNext() + (int32_t)target_size, m_wallet_descriptor.GetEnd());
+ // Calculate the new range_end. next_index can be as high as 2^31-1 on an imported
+ // descriptor and target_size is user controlled, so compute the end in a wider type.
+ // The range is left unchanged if that end does not fit in the int32_t it is stored in.
+ const int64_t target_end{int64_t{m_wallet_descriptor.GetNext()} + target_size};
+ int32_t new_range_end = m_wallet_descriptor.GetEnd();
+ if (target_end <= std::numeric_limits<int32_t>::max()) {
+ new_range_end = std::max(static_cast<int32_t>(target_end), m_wallet_descriptor.GetEnd());
+ }
// If the descriptor is not ranged, we actually just want to fill the first cache item
if (!m_wallet_descriptor.descriptor->IsRange()) {
### src/wallet/test/wallet_tests.cpp
@@ -99,6 +99,7 @@ BOOST_AUTO_TEST_CASE(reject_invalid_descriptor_ranges)
const std::array invalid_ranges{
std::pair{std::pair<int64_t, int64_t>{2, 1}, "Range specified as [begin,end] must not have begin after end"},
+ std::pair{std::pair<int64_t, int64_t>{std::numeric_limits<int64_t>::max(), 0}, "Range specified as [begin,end] must not have begin after end"},
std::pair{std::pair<int64_t, int64_t>{-1, 10}, "Range should be greater or equal than 0"},
std::pair{std::pair<int64_t, int64_t>{0, 1'000'000}, "Range is too large"},
std::pair{std::pair<int64_t, int64_t>{0, std::numeric_limits<int64_t>::max()}, "End of range is too high"},
### test/functional/wallet_importdescriptors.py
@@ -171,6 +171,25 @@ def test_per_item_errors_are_reported_in_order(self):
if not result["success"]:
assert_equal(result["error"]["message"], expected[i][1])
+ def test_keypool_range_bound(self):
+ self.log.info("Test that a -keypool larger than the descriptor range is rejected on import")
+ # Without an explicit range the import falls back to -keypool, which is only
+ # bounded below. A value past the int32_t range_end used to be truncated to a
+ # negative range, aborting the node during keypool top up.
+ self.restart_node(1, extra_args=self.extra_args[1] + ["-keypool=3000000000"])
+ node = self.nodes[1]
+ node.createwallet(wallet_name="keypool_bound", blank=True)
+ wrpc = node.get_wallet_rpc("keypool_bound")
+ desc = descsum_create("wpkh(tprv8ZgxMBicQKsPd7Uf69XL1XwhmjHopUGep8GuEiJDZmbQz6o58LninorQAfcKZWARbtRtfnLcJ5MQ2AtHcQJCCRUcMRvmDUjyEmNUWwx8UbK/0h/0h/*)")
+ self.test_importdesc({"desc": desc, "timestamp": "now"},
+ success=False, error_code=-8, error_message='End of range is too high',
+ warnings=['Range not given, using default keypool range'], wallet=wrpc)
+ # The node survived and no descriptor was added to the wallet.
+ assert_equal(wrpc.listdescriptors()['descriptors'], [])
+ wrpc.unloadwallet()
+ self.restart_node(1, extra_args=self.extra_args[1])
+ self.connect_nodes(0, 1)
+
def test_rescan_fails_import(self):
xpriv = ExtendedPrivateKey.generate().to_string()
@@ -547,6 +566,14 @@ def run_test(self):
self.test_importdesc({"desc": descsum_create(desc), "timestamp": "now", "range": [0, 1000001]},
success=False, error_code=-8, error_message='Range is too large')
+ # The wallet stores the descriptor range as int32_t and range_end is exclusive,
+ # so an inclusive endpoint of 2^31-1 has no representable end. It used to be
+ # truncated to a negative range_end, which aborted the node during keypool top up.
+ # Use an xpub: w1 rejects the xpriv above before the descriptor is added.
+ self.test_importdesc({"desc": descsum_create("wpkh(" + xpub + "/0/*)"), "timestamp": "now",
+ "range": [2**31 - 1, 2**31 - 1]},
+ success=False, error_code=-8, error_message='End of range is too high')
+
self.log.info("Verify we can only extend descriptor's range")
range_request = {"desc": descsum_create(desc), "timestamp": "now", "range": [5, 10], 'active': True}
self.test_importdesc(range_request, wallet=wpriv, success=True)
@@ -1146,6 +1173,7 @@ def run_test(self):
self.test_import_unused_key_existing()
self.test_import_unused_noprivs()
self.test_per_item_errors_are_reported_in_order()
+ self.test_keypool_range_bound()
self.test_rescan_fails_import()
if __name__ == '__main__':
### test/functional/wallet_keypool.py
@@ -25,6 +25,28 @@ def skip_test_if_missing_module(self):
def run_test(self):
nodes = self.nodes
+
+ # A refill to INT32_MAX only overflows the range end once a descriptor has advanced
+ # past index 0, because at next_index 0 the sum is exactly INT32_MAX. Advance every
+ # descriptor by one first so that the addition in TopUpWithDB is 1 + INT32_MAX.
+ nodes[0].createwallet(wallet_name="keypool_overflow")
+ overflow_wallet = nodes[0].get_wallet_rpc("keypool_overflow")
+ for address_type in ["legacy", "p2sh-segwit", "bech32", "bech32m"]:
+ overflow_wallet.getnewaddress(address_type=address_type)
+ overflow_wallet.getrawchangeaddress(address_type=address_type)
+ descriptors_before = overflow_wallet.listdescriptors()["descriptors"]
+ assert_equal(sorted({desc["next_index"] for desc in descriptors_before}), [1])
+
+ # The refill cannot be satisfied, so it is reported as an error and the range is left
+ # as it was. Without the bound this addition is undefined behavior, detected by UBSan.
+ info_before = overflow_wallet.getwalletinfo()
+ assert_raises_rpc_error(-4, "Error refreshing keypool.", overflow_wallet.keypoolrefill, 2**31 - 1)
+ info_after = overflow_wallet.getwalletinfo()
+ assert_equal(info_after["keypoolsize"], info_before["keypoolsize"])
+ assert_equal(info_after["keypoolsize_hd_internal"], info_before["keypoolsize_hd_internal"])
+ assert_equal(overflow_wallet.listdescriptors()["descriptors"], descriptors_before)
+ overflow_wallet.unloadwallet()
+
addr_before_encrypting = nodes[0].getnewaddress()
addr_before_encrypting_data = nodes[0].getaddressinfo(addr_before_encrypting)
Why this scored 66/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.