rpc: keep .cookie if it was not generated

Otherwise, starting bitcoind twice may cause the `.cookie`
file generated by the first instance to be deleted by the
second instance shutdown (after failing to obtain a lock).

Github-Pull: #28784
Rebased-From: d95dde9441fb791046394ed3784a840a54ef2ab9
This commit is contained in:
Roman Zeyde 2023-11-03 16:34:42 +02:00 committed by Luke Dashjr
parent 30308cc380
commit 4ec79e3375
2 changed files with 11 additions and 1 deletions

View File

@ -78,6 +78,8 @@ static fs::path GetAuthCookieFile(bool temp=false)
return AbsPathForConfigVal(fs::PathFromString(arg));
}
static std::optional<std::string> g_generated_cookie;
bool GenerateAuthCookie(std::string *cookie_out)
{
const size_t COOKIE_SIZE = 32;
@ -103,6 +105,7 @@ bool GenerateAuthCookie(std::string *cookie_out)
LogPrintf("Unable to rename cookie authentication file %s to %s\n", fs::PathToString(filepath_tmp), fs::PathToString(filepath));
return false;
}
g_generated_cookie = cookie;
LogPrintf("Generated RPC authentication cookie %s\n", fs::PathToString(filepath));
if (cookie_out)
@ -129,7 +132,11 @@ bool GetAuthCookie(std::string *cookie_out)
void DeleteAuthCookie()
{
try {
fs::remove(GetAuthCookieFile());
std::string existing_cookie;
if (GetAuthCookie(&existing_cookie) && g_generated_cookie == existing_cookie) {
// Delete the cookie file if it exists and was generated by this process
fs::remove(GetAuthCookieFile());
}
} catch (const fs::filesystem_error& e) {
LogPrintf("%s: Unable to remove random auth cookie file: %s\n", __func__, fsbridge::get_filesystem_error_message(e));
}

View File

@ -28,6 +28,9 @@ class FilelockTest(BitcoinTestFramework):
expected_msg = f"Error: Cannot obtain a lock on data directory {datadir}. {self.config['environment']['PACKAGE_NAME']} is probably already running."
self.nodes[1].assert_start_raises_init_error(extra_args=[f'-datadir={self.nodes[0].datadir}', '-noserver'], expected_msg=expected_msg)
cookie_file = os.path.join(datadir, ".cookie")
assert os.path.exists(cookie_file) # should not be deleted during the second bitcoind instance shutdown
if self.is_wallet_compiled():
def check_wallet_filelock(descriptors):
wallet_name = ''.join([random.choice(string.ascii_lowercase) for _ in range(6)])