Skip to content

Stratum v2 Template Provider common functionality #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: 2024/06/sv2_connection
Choose a base branch
from
Open
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
10 changes: 5 additions & 5 deletions src/chainparamsbase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ std::unique_ptr<CBaseChainParams> CreateBaseChainParams(const ChainType chain)
{
switch (chain) {
case ChainType::MAIN:
return std::make_unique<CBaseChainParams>("", 8332);
return std::make_unique<CBaseChainParams>("", 8332, 8336);
case ChainType::TESTNET:
return std::make_unique<CBaseChainParams>("testnet3", 18332);
return std::make_unique<CBaseChainParams>("testnet3", 18332, 18336);
case ChainType::TESTNET4:
return std::make_unique<CBaseChainParams>("testnet4", 48332);
return std::make_unique<CBaseChainParams>("testnet4", 48332, 48336);
case ChainType::SIGNET:
return std::make_unique<CBaseChainParams>("signet", 38332);
return std::make_unique<CBaseChainParams>("signet", 38332, 38336);
case ChainType::REGTEST:
return std::make_unique<CBaseChainParams>("regtest", 18443);
return std::make_unique<CBaseChainParams>("regtest", 18443, 18447);
}
assert(false);
}
Expand Down
6 changes: 4 additions & 2 deletions src/chainparamsbase.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ class CBaseChainParams
public:
const std::string& DataDir() const { return strDataDir; }
uint16_t RPCPort() const { return m_rpc_port; }
uint16_t Sv2Port() const { return m_sv2_port; }

CBaseChainParams() = delete;
CBaseChainParams(const std::string& data_dir, uint16_t rpc_port)
: m_rpc_port(rpc_port), strDataDir(data_dir) {}
CBaseChainParams(const std::string& data_dir, uint16_t rpc_port, uint16_t sv2_port)
: m_rpc_port(rpc_port), m_sv2_port(sv2_port), strDataDir(data_dir) {}

private:
const uint16_t m_rpc_port;
const uint16_t m_sv2_port;
std::string strDataDir;
};

Expand Down
1 change: 1 addition & 0 deletions src/init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -663,6 +663,7 @@ void SetupServerArgs(ArgsManager& argsman, bool can_listen_ipc)
argsman.AddArg("-blockreservedweight=<n>", strprintf("Reserve space for the fixed-size block header plus the largest coinbase transaction the mining software may add to the block. (default: %d).", DEFAULT_BLOCK_RESERVED_WEIGHT), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
argsman.AddArg("-blockmintxfee=<amt>", strprintf("Set lowest fee rate (in %s/kvB) for transactions to be included in block creation. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE)), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);
argsman.AddArg("-blockversion=<n>", "Override block version to test forking scenarios", ArgsManager::ALLOW_ANY | ArgsManager::DEBUG_ONLY, OptionsCategory::BLOCK_CREATION);
argsman.AddArg("-coinbaselocktime", strprintf("Set nLockTime to the current block height and nSequence to enforce it (default: %d)", DEFAULT_COINBASE_LOCKTIME), ArgsManager::ALLOW_ANY, OptionsCategory::BLOCK_CREATION);

argsman.AddArg("-rest", strprintf("Accept public REST requests (default: %u)", DEFAULT_REST_ENABLE), ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
argsman.AddArg("-rpcallowip=<ip>", "Allow JSON-RPC connections from specified source. Valid values for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0), a network/CIDR (e.g. 1.2.3.4/24), all ipv4 (0.0.0.0/0), or all ipv6 (::/0). RFC4193 is allowed only if -cjdnsreachable=0. This option can be specified multiple times", ArgsManager::ALLOW_ANY, OptionsCategory::RPC);
Expand Down
26 changes: 26 additions & 0 deletions src/key.h
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ class CKey
ECDHSecret ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift,
const EllSwiftPubKey& our_ellswift,
bool initiating) const;

/** Compute a KeyPair
*
* Wraps a `secp256k1_keypair` type.
Expand All @@ -220,6 +221,31 @@ class CKey
* Merkle root of the script tree).
*/
KeyPair ComputeKeyPair(const uint256* merkle_root) const;

/** Straight-forward serialization of key bytes (and compressed flag).
* Use GetPrivKey() for OpenSSL compatible DER encoding.
*/
template <typename Stream>
void Serialize(Stream& s) const
{
if (!IsValid()) {
throw std::ios_base::failure("invalid key");
}
s << fCompressed;
::Serialize(s, std::span{*this});
}

template <typename Stream>
void Unserialize(Stream& s)
{
s >> fCompressed;
MakeKeyData();
s >> std::span{*keydata};
if (!Check(keydata->data())) {
ClearKeyData();
throw std::ios_base::failure("invalid key");
}
}
};

CKey GenerateRandomKey(bool compressed = true) noexcept;
Expand Down
1 change: 1 addition & 0 deletions src/node/context.h
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ class ChainstateManager;
class ECC_Context;
class NetGroupManager;
class PeerManager;
class Sv2TemplateProvider;
namespace interfaces {
class Chain;
class ChainClient;
Expand Down
9 changes: 7 additions & 2 deletions src/node/miner.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ void ApplyArgsManOptions(const ArgsManager& args, BlockAssembler::Options& optio
}
options.print_modified_fee = args.GetBoolArg("-printpriority", options.print_modified_fee);
options.block_reserved_weight = args.GetIntArg("-blockreservedweight", options.block_reserved_weight);
options.coinbase_locktime = args.GetBoolArg("-coinbaselocktime", DEFAULT_COINBASE_LOCKTIME);
}

void BlockAssembler::resetBlock()
Expand Down Expand Up @@ -161,13 +162,17 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock()
CMutableTransaction coinbaseTx;
coinbaseTx.vin.resize(1);
coinbaseTx.vin[0].prevout.SetNull();
coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
if (m_options.coinbase_locktime) {
coinbaseTx.vin[0].nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; // Make sure timelock is enforced.
}
coinbaseTx.vout.resize(1);
coinbaseTx.vout[0].scriptPubKey = m_options.coinbase_output_script;
coinbaseTx.vout[0].nValue = nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus());
coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0;
Assert(nHeight > 0);
coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
if (m_options.coinbase_locktime) {
coinbaseTx.nLockTime = static_cast<uint32_t>(nHeight - 1);
}
pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx));
pblocktemplate->vchCoinbaseCommitment = m_chainstate.m_chainman.GenerateCoinbaseCommitment(*pblock, pindexPrev);

Expand Down
2 changes: 2 additions & 0 deletions src/node/miner.h
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ class BlockAssembler
// Configuration parameters for the block size
size_t nBlockMaxWeight{DEFAULT_BLOCK_MAX_WEIGHT};
CFeeRate blockMinFeeRate{DEFAULT_BLOCK_MIN_TX_FEE};
// Whether to set nLockTime to the current height
bool coinbase_locktime{DEFAULT_COINBASE_LOCKTIME};
// Whether to call TestBlockValidity() at the end of CreateNewBlock().
bool test_block_validity{true};
bool print_modified_fee{DEFAULT_PRINT_MODIFIED_FEE};
Expand Down
2 changes: 2 additions & 0 deletions src/policy/policy.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ static constexpr unsigned int DEFAULT_BLOCK_RESERVED_WEIGHT{8000};
static constexpr unsigned int MINIMUM_BLOCK_RESERVED_WEIGHT{2000};
/** Default for -blockmintxfee, which sets the minimum feerate for a transaction in blocks created by mining code **/
static constexpr unsigned int DEFAULT_BLOCK_MIN_TX_FEE{1000};
/** Default for -coinbaselocktime, which sets the coinbase nLockTime (and nSequence) in blocks created by mining code **/
static constexpr bool DEFAULT_COINBASE_LOCKTIME{true};
/** The maximum weight for transactions we're willing to relay/mine */
static constexpr int32_t MAX_STANDARD_TX_WEIGHT{400000};
/** The minimum non-witness size for transactions we're willing to relay/mine: one larger than 64 */
Expand Down
2 changes: 2 additions & 0 deletions src/sv2/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ add_library(bitcoin_sv2 STATIC EXCLUDE_FROM_ALL
noise.cpp
transport.cpp
connman.cpp
messages.cpp
template_provider.cpp
)

target_link_libraries(bitcoin_sv2
Expand Down
35 changes: 35 additions & 0 deletions src/sv2/connman.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,41 @@ void Sv2Connman::ProcessSv2Message(const Sv2NetMsg& sv2_net_msg, Sv2Client& clie

break;
}
case Sv2MsgType::SUBMIT_SOLUTION: {
if (!client.m_setup_connection_confirmed && !client.m_coinbase_output_constraints_recv) {
client.m_disconnect_flag = true;
return;
}

node::Sv2SubmitSolutionMsg submit_solution;
try {
ss >> submit_solution;
} catch (const std::exception& e) {
LogPrintLevel(BCLog::SV2, BCLog::Level::Error, "Received invalid SubmitSolution message from client id=%zu: %e\n",
client.m_id, e.what());
return;
}

m_msgproc->SubmitSolution(submit_solution);

break;
}
case Sv2MsgType::REQUEST_TRANSACTION_DATA:
{
node::Sv2RequestTransactionDataMsg request_tx_data;

try {
ss >> request_tx_data;
} catch (const std::exception& e) {
LogPrintLevel(BCLog::SV2, BCLog::Level::Error, "Received invalid RequestTransactionData message from client id=%zu: %e\n",
client.m_id, e.what());
return;
}

m_msgproc->RequestTransactionData(client, request_tx_data);

break;
}
default: {
uint8_t msg_type[1]{uint8_t(sv2_net_msg.m_msg_type)};
LogPrintLevel(BCLog::SV2, BCLog::Level::Warning, "Received unknown message type 0x%s from client id=%zu\n",
Expand Down
18 changes: 18 additions & 0 deletions src/sv2/connman.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ struct Sv2Client
*/
unsigned int m_coinbase_tx_outputs_size;

/**
* Tracks the best template in the Template Provider m_block_template_cache map.
* Not guaranteed to still exist.
*/
uint64_t m_best_template_id = 0;

explicit Sv2Client(size_t id, std::unique_ptr<Sv2Transport> transport) :
m_id{id}, m_transport{std::move(transport)} {};

Expand All @@ -75,6 +81,18 @@ struct Sv2Client
class Sv2EventsInterface
{
public:
/**
* We received and successfully parsed a RequestTransactionData message.
* Deal with it and respond with either RequestTransactionData.Success or
* RequestTransactionData.Error.
*/
virtual void RequestTransactionData(Sv2Client& client, node::Sv2RequestTransactionDataMsg msg) = 0;

/**
* We received and successfully parsed a SubmitSolution message.
*/
virtual void SubmitSolution(node::Sv2SubmitSolutionMsg solution) = 0;

virtual ~Sv2EventsInterface() = default;
};

Expand Down
41 changes: 41 additions & 0 deletions src/sv2/messages.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <sv2/messages.h>

#include <arith_uint256.h>
#include <primitives/block.h>
#include <primitives/transaction.h>

node::Sv2NewTemplateMsg::Sv2NewTemplateMsg(const CBlockHeader& header, const CTransactionRef coinbase_tx, std::vector<uint256> coinbase_merkle_path, int witness_commitment_index, uint64_t template_id, bool future_template)
: m_template_id{template_id}, m_future_template{future_template}
{
m_version = header.nVersion;

m_coinbase_tx_version = coinbase_tx->CURRENT_VERSION;
m_coinbase_prefix = coinbase_tx->vin[0].scriptSig;
m_coinbase_tx_input_sequence = coinbase_tx->vin[0].nSequence;

// The coinbase nValue already contains the nFee + the Block Subsidy when built using CreateBlock().
m_coinbase_tx_value_remaining = static_cast<uint64_t>(coinbase_tx->vout[0].nValue);

m_coinbase_tx_outputs_count = 0;
if (witness_commitment_index != NO_WITNESS_COMMITMENT) {
m_coinbase_tx_outputs_count = 1;

std::vector<CTxOut> coinbase_tx_outputs{coinbase_tx->vout[witness_commitment_index]};
m_coinbase_tx_outputs = coinbase_tx_outputs;
}

m_coinbase_tx_locktime = coinbase_tx->nLockTime;

for (const auto& hash : coinbase_merkle_path) {
m_merkle_path.push_back(hash);
}

}

node::Sv2SetNewPrevHashMsg::Sv2SetNewPrevHashMsg(const CBlockHeader& header, uint64_t template_id) : m_template_id{template_id}
{
m_prev_hash = header.hashPrevBlock;
m_header_timestamp = header.nTime;
m_nBits = header.nBits;
m_target = ArithToUint256(arith_uint256().SetCompact(header.nBits));
}
Loading
Loading