mirror of
https://github.com/bitcoin/bitcoin.git
synced 2026-05-28 14:55:22 +02:00
kernel: Add Block Header serialization method
Add `btck_block_header_to_bytes` serialization method to serialize a `btck_BlockHeader` into an 80-byte buffer using `SpanWriter` to ensure zero-allocation serialization.
This commit is contained in:
@@ -1390,6 +1390,16 @@ uint32_t btck_block_header_get_nonce(const btck_BlockHeader* header)
|
||||
return btck_BlockHeader::get(header).nNonce;
|
||||
}
|
||||
|
||||
int btck_block_header_to_bytes(const btck_BlockHeader* header, unsigned char output[80])
|
||||
{
|
||||
try {
|
||||
SpanWriter{std::as_writable_bytes(std::span{output, 80})} << btck_BlockHeader::get(header);
|
||||
return 0;
|
||||
} catch (...) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
void btck_block_header_destroy(btck_BlockHeader* header)
|
||||
{
|
||||
delete header;
|
||||
|
||||
@@ -1768,6 +1768,17 @@ BITCOINKERNEL_API int32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_get
|
||||
BITCOINKERNEL_API uint32_t BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_get_nonce(
|
||||
const btck_BlockHeader* header) BITCOINKERNEL_ARG_NONNULL(1);
|
||||
|
||||
/**
|
||||
* @brief Serializes the btck_BlockHeader to bytes.
|
||||
* This is consensus serialization that is also used for the P2P network.
|
||||
*
|
||||
* @param[in] header Non-null.
|
||||
* @param[out] output The serialized block header (80 bytes).
|
||||
* @return 0 on success.
|
||||
*/
|
||||
BITCOINKERNEL_API int BITCOINKERNEL_WARN_UNUSED_RESULT btck_block_header_to_bytes(
|
||||
const btck_BlockHeader* header, unsigned char output[80]) BITCOINKERNEL_ARG_NONNULL(1, 2);
|
||||
|
||||
/**
|
||||
* Destroy the btck_BlockHeader.
|
||||
*/
|
||||
|
||||
@@ -746,6 +746,16 @@ public:
|
||||
{
|
||||
return btck_block_header_get_nonce(impl());
|
||||
}
|
||||
|
||||
std::array<std::byte, 80> ToBytes() const
|
||||
{
|
||||
std::array<std::byte, 80> header;
|
||||
int res{btck_block_header_to_bytes(impl(), reinterpret_cast<unsigned char*>(header.data()))};
|
||||
if (res != 0) {
|
||||
throw std::runtime_error("Failed to serialize block header");
|
||||
}
|
||||
return header;
|
||||
}
|
||||
};
|
||||
|
||||
class BlockHeaderView : public View<btck_BlockHeader>, public BlockHeaderApi<BlockHeaderView>
|
||||
|
||||
Reference in New Issue
Block a user