Skip to content
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

feat/blocktxn #154

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
128 changes: 128 additions & 0 deletions src/network/protocol/messages/blocktxn.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
const std = @import("std");
const protocol = @import("../lib.zig");

const Sha256 = std.crypto.hash.sha2.Sha256;
const BlockHeader = @import("../../../types/block_header.zig");
const CompactSizeUint = @import("bitcoin-primitives").types.CompatSizeUint;
const genericChecksum = @import("lib.zig").genericChecksum;
/// BlockTxnMessage represents the "BlockTxn" message
guha-rahul marked this conversation as resolved.
Show resolved Hide resolved
///
/// https://developer.bitcoin.org/reference/p2p_networking.html#blocktxn
pub const BlockTxnMessage = struct {
block_hash: [32]u8,
indexes: []CompactSizeUint,
guha-rahul marked this conversation as resolved.
Show resolved Hide resolved

const Self = @This();

pub fn name() *const [12]u8 {
return protocol.CommandNames.BLOCKTXN ++ [_]u8{0} ** 4;
}

/// Returns the message checksum
pub fn checksum(self: *const Self) [4]u8 {
return genericChecksum(self);
}

/// Free the allocated memory
pub fn deinit(self: *const Self, allocator: std.mem.Allocator) void {
allocator.free(self.indexes);
}

/// Serialize the message as bytes and write them to the Writer.
pub fn serializeToWriter(self: *const Self, w: anytype) !void {
comptime {
if (!std.meta.hasFn(@TypeOf(w), "writeInt")) @compileError("Expects r to have fn 'writeInt'.");
if (!std.meta.hasFn(@TypeOf(w), "writeAll")) @compileError("Expects r to have fn 'writeAll'.");
}
try w.writeAll(&self.block_hash);
const indexes_count = CompactSizeUint.new(self.indexes.len);
try indexes_count.encodeToWriter(w);
for (self.indexes) |*index| {
try index.encodeToWriter(w);
}
}
/// Serialize a message as bytes and write them to the buffer.
///
/// buffer.len must be >= than self.hintSerializedLen()
pub fn serializeToSlice(self: *const Self, buffer: []u8) !void {
var fbs = std.io.fixedBufferStream(buffer);
try self.serializeToWriter(fbs.writer());
}

/// Serialize a message as bytes and return them.
pub fn serialize(self: *const Self, allocator: std.mem.Allocator) ![]u8 {
guha-rahul marked this conversation as resolved.
Show resolved Hide resolved
const serialized_len = self.hintSerializedLen();
const ret = try allocator.alloc(u8, serialized_len);
errdefer allocator.free(ret);

try self.serializeToSlice(ret);

return ret;
}

/// Returns the hint of the serialized length of the message.
pub fn hintSerializedLen(self: *const Self) usize {
// 32 bytes for the block header
guha-rahul marked this conversation as resolved.
Show resolved Hide resolved
const fixed_length = 32;

const indexes_count_length: usize = CompactSizeUint.new(self.indexes.len).hint_encoded_len();

var compact_indexes_length: usize = 0;
for (self.indexes) |index| {
compact_indexes_length += index.hint_encoded_len();
}

const variable_length = indexes_count_length + compact_indexes_length;

return fixed_length + variable_length;
}

pub fn deserializeReader(allocator: std.mem.Allocator, r: anytype) !Self {
var blocktxn_message: Self = undefined;
try r.readNoEof(&blocktxn_message.block_hash);

const indexes_count = try CompactSizeUint.decodeReader(r);
blocktxn_message.indexes = try allocator.alloc(CompactSizeUint, indexes_count.value());
errdefer allocator.free(blocktxn_message.indexes);

for (blocktxn_message.indexes) |*index| {
index.* = try CompactSizeUint.decodeReader(r);
}

return blocktxn_message;
}

/// Deserialize bytes into a `BlockTxnMessage`
pub fn deserializeSlice(allocator: std.mem.Allocator, bytes: []const u8) !Self {
guha-rahul marked this conversation as resolved.
Show resolved Hide resolved
var fbs = std.io.fixedBufferStream(bytes);
return try Self.deserializeReader(allocator, fbs.reader());
}

pub fn new(block_hash: [32]u8, indexes: []CompactSizeUint) Self {
return .{
.block_hash = block_hash,
.indexes = indexes,
};
}
};

test "BlockTxnMessage serialization and deserialization" {
const test_allocator = std.testing.allocator;

const block_hash: [32]u8 = [_]u8{0} ** 32;
const indexes = try test_allocator.alloc(CompactSizeUint, 1);
indexes[0] = CompactSizeUint.new(123);
const msg = BlockTxnMessage.new(block_hash, indexes);

defer msg.deinit(test_allocator);

const serialized = try msg.serialize(test_allocator);
defer test_allocator.free(serialized);

const deserialized = try BlockTxnMessage.deserializeSlice(test_allocator, serialized);
defer deserialized.deinit(test_allocator);

try std.testing.expectEqual(msg.block_hash, deserialized.block_hash);
try std.testing.expectEqual(msg.indexes[0].value(), msg.indexes[0].value());
try std.testing.expectEqual(msg.hintSerializedLen(), 32 + 1 + 1);
}
7 changes: 7 additions & 0 deletions src/network/protocol/messages/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const Sha256 = std.crypto.hash.sha2.Sha256;
pub const NotFoundMessage = @import("notfound.zig").NotFoundMessage;
pub const SendHeadersMessage = @import("sendheaders.zig").SendHeadersMessage;
pub const FilterLoadMessage = @import("filterload.zig").FilterLoadMessage;
pub const BlockTxnMessage = @import("blocktxn.zig").BlockTxnMessage;

pub const InventoryVector = struct {
type: u32,
Expand Down Expand Up @@ -65,6 +66,7 @@ pub const MessageTypes = enum {
notfound,
sendheaders,
filterload,
blocktxn,
};

pub const Message = union(MessageTypes) {
Expand All @@ -84,6 +86,7 @@ pub const Message = union(MessageTypes) {
notfound: NotFoundMessage,
sendheaders: SendHeadersMessage,
filterload: FilterLoadMessage,
blocktxn: BlockTxnMessage,

pub fn name(self: Message) *const [12]u8 {
return switch (self) {
Expand All @@ -103,6 +106,7 @@ pub const Message = union(MessageTypes) {
.notfound => |m| @TypeOf(m).name(),
.sendheaders => |m| @TypeOf(m).name(),
.filterload => |m| @TypeOf(m).name(),
.blocktxn => |m| @TypeOf(m).name(),
};
}

Expand All @@ -124,6 +128,7 @@ pub const Message = union(MessageTypes) {
.notfound => {},
.sendheaders => {},
.filterload => {},
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it can be removed, because managed in the else.

.blocktxn => |*m| m.deinit(allocator),
}
}

Expand All @@ -145,6 +150,7 @@ pub const Message = union(MessageTypes) {
.notfound => |*m| m.checksum(),
.sendheaders => |*m| m.checksum(),
.filterload => |*m| m.checksum(),
.blocktxn => |*m| m.checksum(),
};
}

Expand All @@ -166,6 +172,7 @@ pub const Message = union(MessageTypes) {
.notfound => |m| m.hintSerializedLen(),
.sendheaders => |m| m.hintSerializedLen(),
.filterload => |*m| m.hintSerializedLen(),
.blocktxn => |*m| m.hintSerializedLen(),
};
}
};
Expand Down
8 changes: 8 additions & 0 deletions src/network/protocol/messages/merkleblock.zig
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ pub const MerkleBlockMessage = struct {

/// Serialize the message as bytes and write them to the Writer.
pub fn serializeToWriter(self: *const Self, w: anytype) !void {
comptime {
if (!std.meta.hasFn(@TypeOf(w), "writeInt")) @compileError("Expects w to have fn 'writeInt'.");
if (!std.meta.hasFn(@TypeOf(w), "writeAll")) @compileError("Expects w to have fn 'writeAll'.");
}
try self.block_header.serializeToWriter(w);
try w.writeInt(u32, self.transaction_count, .little);
const hash_count = CompactSizeUint.new(self.hashes.len);
Expand Down Expand Up @@ -78,6 +82,10 @@ pub const MerkleBlockMessage = struct {
}

pub fn deserializeReader(allocator: std.mem.Allocator, r: anytype) !Self {
comptime {
if (!std.meta.hasFn(@TypeOf(r), "readInt")) @compileError("Expects r to have fn 'readInt'.");
if (!std.meta.hasFn(@TypeOf(r), "readNoEof")) @compileError("Expects r to have fn 'readNoEof'.");
}
var merkle_block_message: Self = undefined;
merkle_block_message.block_header = try BlockHeader.deserializeReader(r);
merkle_block_message.transaction_count = try r.readInt(u32, .little);
Expand Down
37 changes: 36 additions & 1 deletion src/network/wire/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ pub const Error = error{
};

const BlockHeader = @import("../../types/block_header.zig");
/// Return the checksum of a slice
const CompactSizeUint = @import("bitcoin-primitives").types.CompatSizeUint;
guha-rahul marked this conversation as resolved.
Show resolved Hide resolved
// Return the checksum of a slice
guha-rahul marked this conversation as resolved.
Show resolved Hide resolved
///
/// Use it on serialized messages to compute the header's value
fn computePayloadChecksum(payload: []u8) [4]u8 {
Expand Down Expand Up @@ -141,6 +142,8 @@ pub fn receiveMessage(
protocol.messages.Message{ .sendheaders = try protocol.messages.SendHeadersMessage.deserializeReader(allocator, r) }
else if (std.mem.eql(u8, &command, protocol.messages.FilterLoadMessage.name()))
protocol.messages.Message{ .filterload = try protocol.messages.FilterLoadMessage.deserializeReader(allocator, r) }
else if (std.mem.eql(u8, &command, protocol.messages.BlockTxnMessage.name()))
protocol.messages.Message{ .blocktxn = try protocol.messages.BlockTxnMessage.deserializeReader(allocator, r) }
else {
try r.skipBytes(payload_len, .{}); // Purge the wire
return error.UnknownMessage;
Expand Down Expand Up @@ -579,3 +582,35 @@ test "ok_send_sendcmpct_message" {
else => unreachable,
}
}
test "ok_send_blocktxn_message" {
const Config = @import("../../config/config.zig").Config;
const ArrayList = std.ArrayList;
const test_allocator = std.testing.allocator;
const BlockTxnMessage = protocol.messages.BlockTxnMessage;

var list: std.ArrayListAligned(u8, null) = ArrayList(u8).init(test_allocator);
defer list.deinit();

const block_hash = [_]u8{0} ** 32;
const indexes = try test_allocator.alloc(CompactSizeUint, 1);
indexes[0] = CompactSizeUint.new(1000);
defer test_allocator.free(indexes);
const message = BlockTxnMessage.new(block_hash, indexes);

var received_message = try write_and_read_message(
test_allocator,
&list,
Config.BitcoinNetworkId.MAINNET,
Config.PROTOCOL_VERSION,
message,
) orelse unreachable;
defer received_message.deinit(test_allocator);

switch (received_message) {
.blocktxn => {
try std.testing.expectEqual(message.block_hash, received_message.blocktxn.block_hash);
try std.testing.expectEqual(indexes[0].value(), received_message.blocktxn.indexes[0].value());
},
else => unreachable,
}
}
Loading