Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/bitcoin-chainstate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ int main(int argc, char* argv[])
// SETUP: Chainstate
const ChainstateManager::Options chainman_opts{
.chainparams = chainparams,
.adjusted_time_callback = static_cast<int64_t (*)()>(GetTime),
};
ChainstateManager chainman{chainman_opts};

Expand Down
1 change: 0 additions & 1 deletion src/init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2021,7 +2021,6 @@ bool AppInitMain(NodeContext& node, interfaces::BlockAndHeaderTipInfo* tip_info)

const ChainstateManager::Options chainman_opts{
.chainparams = chainparams,
.adjusted_time_callback = GetAdjustedTime,
};
node.chainman = std::make_unique<ChainstateManager>(chainman_opts);
ChainstateManager& chainman = *node.chainman;
Expand Down
2 changes: 0 additions & 2 deletions src/kernel/chainstatemanager_opts.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
#define BITCOIN_KERNEL_CHAINSTATEMANAGER_OPTS_H

#include <cstdint>
#include <functional>

class CChainParams;

Expand All @@ -19,7 +18,6 @@ namespace kernel {
*/
struct ChainstateManagerOpts {
const CChainParams& chainparams;
const std::function<int64_t()> adjusted_time_callback{nullptr};
};

} // namespace kernel
Expand Down
8 changes: 4 additions & 4 deletions src/net_processing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1406,7 +1406,7 @@ bool PeerManagerImpl::TipMayBeStale()

bool PeerManagerImpl::CanDirectFetch()
{
return m_chainman.ActiveChain().Tip()->GetBlockTime() > GetAdjustedTime() - m_chainparams.GetConsensus().nPowTargetSpacing * 20;
return m_chainman.ActiveChain().Tip()->GetBlockTime() > GetTime() - m_chainparams.GetConsensus().nPowTargetSpacing * 20;
}

static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Expand Down Expand Up @@ -6180,7 +6180,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)

if (!state.fSyncStarted && CanServeBlocks(*peer) && !fImporting && !fReindex && pto->CanRelay()) {
// Only actively request headers from a single peer, unless we're close to end of initial download.
if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->GetBlockTime() > GetAdjustedTime() - nMaxTipAge) {
if ((nSyncStarted == 0 && sync_blocks_and_headers_from_peer) || m_chainman.m_best_header->GetBlockTime() > GetTime() - nMaxTipAge) {
const CBlockIndex* pindexStart = m_chainman.m_best_header;
/* If possible, start at the block preceding the currently
best known header. This ensures that we always get a
Expand All @@ -6201,7 +6201,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
// Convert HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER to microseconds before scaling
// to maintain precision
std::chrono::microseconds{HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER} *
(GetAdjustedTime() - m_chainman.m_best_header->GetBlockTime()) / consensusParams.nPowTargetSpacing
(GetTime() - m_chainman.m_best_header->GetBlockTime()) / consensusParams.nPowTargetSpacing
);
nSyncStarted++;
}
Expand Down Expand Up @@ -6582,7 +6582,7 @@ bool PeerManagerImpl::SendMessages(CNode* pto)
// Check for headers sync timeouts
if (state.fSyncStarted && state.m_headers_sync_timeout < std::chrono::microseconds::max()) {
// Detect whether this is a stalling initial-headers-sync peer
if (m_chainman.m_best_header->GetBlockTime() <= GetAdjustedTime() - nMaxTipAge) {
if (m_chainman.m_best_header->GetBlockTime() <= GetTime() - nMaxTipAge) {
if (current_time > state.m_headers_sync_timeout && nSyncStarted == 1 && (m_num_preferred_download_peers - state.fPreferredDownload >= 1)) {
// Disconnect a peer (without NetPermissionFlags::NoBan permission) if it is our only sync peer,
// and we have others we could be using instead.
Expand Down
6 changes: 3 additions & 3 deletions src/node/miner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ namespace node {
int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev)
{
int64_t nOldTime = pblock->nTime;
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast() + 1, GetAdjustedTime());
int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast() + 1, GetTime());

if (nOldTime < nNewTime) {
pblock->nTime = nNewTime;
Expand Down Expand Up @@ -218,7 +218,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
pblock->nVersion = gArgs.GetIntArg("-blockversion", pblock->nVersion);
}

pblock->nTime = GetAdjustedTime();
pblock->nTime = GetTime();
m_lock_time_cutoff = pindexPrev->GetMedianTimePast();

if (fDIP0003Active_context) {
Expand Down Expand Up @@ -334,7 +334,7 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(*pblock->vtx[0]);

BlockValidationState state;
if (!TestBlockValidity(state, m_chainlocks, m_evoDb, chainparams, m_chainstate, *pblock, pindexPrev, GetAdjustedTime, false, false)) {
if (!TestBlockValidity(state, m_chainlocks, m_evoDb, chainparams, m_chainstate, *pblock, pindexPrev, false, false)) {
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
}
int64_t nTime2 = GetTimeMicros();
Expand Down
4 changes: 2 additions & 2 deletions src/rpc/mining.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ static RPCHelpMan generateblock()

BlockValidationState state;
if (!TestBlockValidity(state, *CHECK_NONFATAL(node.chainlocks), *CHECK_NONFATAL(node.evodb), chainman.GetParams(), active_chainstate,
block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), GetAdjustedTime, false, false)) {
block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), false, false)) {
throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.GetRejectReason()));
}
}
Expand Down Expand Up @@ -698,7 +698,7 @@ static RPCHelpMan getblocktemplate()
return "inconclusive-not-best-prevblk";
BlockValidationState state;
TestBlockValidity(state, *CHECK_NONFATAL(node.chainlocks), *CHECK_NONFATAL(node.evodb), chainman.GetParams(), active_chainstate,
block, pindexPrev, GetAdjustedTime, false, true);
block, pindexPrev, false, true);
return BIP22ValidationResult(state);
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/bls_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ BOOST_AUTO_TEST_CASE(v19_boundary_validation_failure_restores_bls_scheme)
BlockValidationState state;
BOOST_CHECK(!TestBlockValidity(state, *Assert(setup.m_node.chainlocks), *Assert(setup.m_node.evodb), Params(),
chainman.ActiveChainstate(), proposal_block, chainman.ActiveChain().Tip(),
GetAdjustedTime, /*fCheckPOW=*/true, /*fCheckMerkleRoot=*/true));
/*fCheckPOW=*/true, /*fCheckMerkleRoot=*/true));
BOOST_CHECK_EQUAL(state.GetRejectReason(), "bad-txns-inputs-missingorspent");
}
BOOST_CHECK(bls::bls_legacy_scheme.load());
Expand Down
1 change: 0 additions & 1 deletion src/test/util/setup_common.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,6 @@ ChainTestingSetup::ChainTestingSetup(const std::string& chainName, const std::ve

const ChainstateManager::Options chainman_opts{
.chainparams = chainparams,
.adjusted_time_callback = GetAdjustedTime,
};
m_node.chainman = std::make_unique<ChainstateManager>(chainman_opts);
m_node.chainman->m_blockman.m_block_tree_db = std::make_unique<CBlockTreeDB>(m_cache_sizes.block_tree_db, true);
Expand Down
14 changes: 6 additions & 8 deletions src/validation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2169,8 +2169,7 @@ bool CChainState::ConnectBlock(const CBlock& block, BlockValidationState& state,
// for one approach that was used for BIP 141 deployment).
// Also, currently the rule against blocks more than 2 hours in the future
// is enforced in ContextualCheckBlockHeader(); we wouldn't want to
// re-enforce that rule here (at least until we make it impossible for
// m_adjusted_time_callback() to go backward).
// re-enforce that rule here.
if (!CheckBlock(block, state, m_params.GetConsensus(), !fJustCheck, !fJustCheck)) {
if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED) {
// We don't write down blocks to disk if they may have been
Expand Down Expand Up @@ -3915,7 +3914,7 @@ bool IsBlockMutated(const CBlock& block)
* in ConnectBlock().
* Note that -reindex-chainstate skips the validation that happens here!
*/
static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, BlockManager& blockman, const ChainstateManager& chainman, const CBlockIndex* pindexPrev, int64_t nAdjustedTime) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidationState& state, BlockManager& blockman, const ChainstateManager& chainman, const CBlockIndex* pindexPrev) EXCLUSIVE_LOCKS_REQUIRED(::cs_main)
{
AssertLockHeld(::cs_main);
assert(pindexPrev != nullptr);
Expand Down Expand Up @@ -3955,8 +3954,8 @@ static bool ContextualCheckBlockHeader(const CBlockHeader& block, BlockValidatio
return state.Invalid(BlockValidationResult::BLOCK_INVALID_HEADER, "time-too-old", strprintf("block's timestamp is too early %d %d", block.GetBlockTime(), pindexPrev->GetMedianTimePast()));

// Check timestamp
if (block.GetBlockTime() > nAdjustedTime + MAX_FUTURE_BLOCK_TIME)
return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", strprintf("block timestamp too far in the future %d %d", block.GetBlockTime(), nAdjustedTime + 2 * 60 * 60));
if (block.GetBlockTime() > GetTime() + MAX_FUTURE_BLOCK_TIME)
return state.Invalid(BlockValidationResult::BLOCK_TIME_FUTURE, "time-too-new", strprintf("block timestamp too far in the future %d %d", block.GetBlockTime(), GetTime() + MAX_FUTURE_BLOCK_TIME));

// Reject blocks with outdated version
if ((block.nVersion < 2 && DeploymentActiveAfter(pindexPrev, chainman.GetConsensus(), Consensus::DEPLOYMENT_HEIGHTINCB)) ||
Expand Down Expand Up @@ -4094,7 +4093,7 @@ bool ChainstateManager::AcceptBlockHeader(const CBlockHeader& block, BlockValida
return state.Invalid(BlockValidationResult::BLOCK_CHAINLOCK, "bad-prevblk-chainlock");
}

if (!ContextualCheckBlockHeader(block, state, m_blockman, *this, pindexPrev, m_adjusted_time_callback())) {
if (!ContextualCheckBlockHeader(block, state, m_blockman, *this, pindexPrev)) {
LogPrint(BCLog::VALIDATION, "%s: Consensus::ContextualCheckBlockHeader: %s, %s\n", __func__, hash.ToString(), state.ToString());
return false;
}
Expand Down Expand Up @@ -4360,7 +4359,6 @@ bool TestBlockValidity(BlockValidationState& state,
CChainState& chainstate,
const CBlock& block,
CBlockIndex* pindexPrev,
const std::function<int64_t()>& adjusted_time_callback,
bool fCheckPOW,
bool fCheckMerkleRoot)
{
Expand All @@ -4384,7 +4382,7 @@ bool TestBlockValidity(BlockValidationState& state,
auto dbTx = evoDb.BeginTransaction();

// NOTE: CheckBlockHeader is called by CheckBlock
if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman, chainstate.m_chainman, pindexPrev, adjusted_time_callback()))
if (!ContextualCheckBlockHeader(block, state, chainstate.m_blockman, chainstate.m_chainman, pindexPrev))
return error("%s: Consensus::ContextualCheckBlockHeader: %s", __func__, state.ToString());
if (!CheckBlock(block, state, chainparams.GetConsensus(), fCheckPOW, fCheckMerkleRoot))
return error("%s: Consensus::CheckBlock: %s", __func__, state.ToString());
Expand Down
4 changes: 0 additions & 4 deletions src/validation.h
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,6 @@ bool TestBlockValidity(BlockValidationState& state,
CChainState& chainstate,
const CBlock& block,
CBlockIndex* pindexPrev,
const std::function<int64_t()>& adjusted_time_callback,
bool fCheckPOW = true,
bool fCheckMerkleRoot = true) EXCLUSIVE_LOCKS_REQUIRED(cs_main);

Expand Down Expand Up @@ -904,8 +903,6 @@ class ChainstateManager

const CChainParams m_chainparams;

const std::function<int64_t()> m_adjusted_time_callback;

//! Internal helper for ActivateSnapshot().
[[nodiscard]] bool PopulateAndValidateSnapshot(
CChainState& snapshot_chainstate,
Expand All @@ -930,7 +927,6 @@ class ChainstateManager

explicit ChainstateManager(const Options& opts)
: m_chainparams{opts.chainparams},
m_adjusted_time_callback{Assert(opts.adjusted_time_callback)},
m_blockman{{opts.chainparams}} {};

const CChainParams& GetParams() const { return m_chainparams; }
Expand Down
4 changes: 4 additions & 0 deletions test/functional/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ don't have test cases for.
`set_test_params()`, `add_options()` and `setup_xxxx()` methods at the top of
the subclass, then locally-defined helper methods, then the `run_test()` method.
- Use `f'{x}'` for string formatting in preference to `'{}'.format(x)` or `'%s' % x`.
- Use `platform.system()` for detecting the running operating system and `os.name` to
check whether it's a POSIX system (see also the `skip_if_platform_not_{linux,posix}`
methods in the `BitcoinTestFramework` class, which can be used to skip a whole test
depending on the platform).

#### Naming guidelines

Expand Down
10 changes: 3 additions & 7 deletions test/functional/feature_bind_extra.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,12 @@
that bind happens on the expected ports.
"""

import sys

from test_framework.netutil import (
addr_to_hex,
get_bind_addrs,
)
from test_framework.test_framework import (
BitcoinTestFramework,
SkipTest,
)
from test_framework.util import (
assert_equal,
Expand All @@ -32,12 +29,11 @@ def set_test_params(self):
self.bind_to_localhost_only = False
self.num_nodes = 2

def setup_network(self):
def skip_test_if_missing_module(self):
# Due to OS-specific network stats queries, we only run on Linux.
self.log.info("Checking for Linux")
if not sys.platform.startswith('linux'):
raise SkipTest("This test can only be run on Linux.")
self.skip_if_platform_not_linux()

def setup_network(self):
loopback_ipv4 = addr_to_hex("127.0.0.1")

# Start custom ports by reusing unused p2p ports
Expand Down
4 changes: 2 additions & 2 deletions test/functional/feature_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Stress tests related to node initialization."""
import os
import platform
from pathlib import Path
from random import randint
import shutil
Expand Down Expand Up @@ -37,7 +37,7 @@ def run_test(self):
# and other approaches (like below) don't work:
#
# os.kill(node.process.pid, signal.CTRL_C_EVENT)
if os.name == 'nt':
if platform.system() == 'Windows':
raise SkipTest("can't SIGTERM on Windows")

self.stop_node(0)
Expand Down
9 changes: 5 additions & 4 deletions test/functional/feature_notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test the -alertnotify, -blocknotify, -chainlocknotify, -instantsendnotify and -walletnotify options."""
import os
import platform

from test_framework.address import ADDRESS_BCRT1_UNSPENDABLE

Expand All @@ -15,13 +16,13 @@

# Linux allow all characters other than \x00
# Windows disallow control characters (0-31) and /\?%:|"<>
FILE_CHAR_START = 32 if os.name == 'nt' else 1
FILE_CHAR_START = 32 if platform.system() == 'Windows' else 1
FILE_CHAR_END = 128
FILE_CHARS_DISALLOWED = '/\\?%*:|"<>' if os.name == 'nt' else '/'
FILE_CHARS_DISALLOWED = '/\\?%*:|"<>' if platform.system() == 'Windows' else '/'
UNCONFIRMED_HASH_STRING = 'unconfirmed'

def notify_outputname(walletname, txid):
return txid if os.name == 'nt' else f'{walletname}_{txid}'
return txid if platform.system() == 'Windows' else f'{walletname}_{txid}'


class NotificationsTest(DashTestFramework):
Expand Down Expand Up @@ -165,7 +166,7 @@ def expect_wallet_notify(self, tx_details):
# Universal newline ensures '\n' on 'nt'
assert_equal(text[-1], '\n')
text = text[:-1]
if os.name == 'nt':
if platform.system() == 'Windows':
# On Windows, echo as above will append a whitespace
assert_equal(text[-1], ' ')
text = text[:-1]
Expand Down
11 changes: 4 additions & 7 deletions test/functional/rpc_bind.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test running dashd with the -rpcbind and -rpcallowip options."""

import sys

from test_framework.netutil import all_interfaces, addr_to_hex, get_bind_addrs, test_ipv6_local
from test_framework.test_framework import BitcoinTestFramework, SkipTest
from test_framework.util import assert_equal, assert_raises_rpc_error, get_rpc_proxy, rpc_port, rpc_url
Expand All @@ -17,6 +15,10 @@ def set_test_params(self):
self.num_nodes = 1
self.supports_cli = False

def skip_test_if_missing_module(self):
# due to OS-specific network stats queries, this test works only on Linux
self.skip_if_platform_not_linux()

def setup_network(self):
self.add_nodes(self.num_nodes, None)

Expand Down Expand Up @@ -61,14 +63,9 @@ def run_allowip_test(self, allow_ips, rpchost, rpcport):
self.stop_nodes()

def run_test(self):
# due to OS-specific network stats queries, this test works only on Linux
if sum([self.options.run_ipv4, self.options.run_ipv6, self.options.run_nonloopback]) > 1:
raise AssertionError("Only one of --ipv4, --ipv6 and --nonloopback can be set")

self.log.info("Check for linux")
if not sys.platform.startswith('linux'):
raise SkipTest("This test can only be run on linux.")

self.log.info("Check for ipv6")
have_ipv6 = test_ipv6_local()
if not have_ipv6 and not (self.options.run_ipv4 or self.options.run_nonloopback):
Expand Down
3 changes: 2 additions & 1 deletion test/functional/test_framework/p2p.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
from collections import defaultdict
from io import BytesIO
import logging
import platform
import struct
import sys
import threading
Expand Down Expand Up @@ -786,7 +787,7 @@ def __init__(self):

NetworkThread.listeners = {}
NetworkThread.protos = {}
if sys.platform == 'win32':
if platform.system() == 'Windows':
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
NetworkThread.network_event_loop = asyncio.new_event_loop()

Expand Down
4 changes: 2 additions & 2 deletions test/functional/test_framework/test_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,13 @@
import json
import logging
import os.path
import platform
import re
import subprocess
import tempfile
import time
import urllib.parse
import shlex
import sys
import collections
from pathlib import Path

Expand Down Expand Up @@ -573,7 +573,7 @@ def test_success(cmd):
cmd, shell=True,
stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) == 0

if not sys.platform.startswith('linux'):
if platform.system() != 'Linux':
self.log.warning("Can't profile with perf; only available on Linux platforms")
return None

Expand Down
Loading