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 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
115 changes: 115 additions & 0 deletions src/network/protocol/messages/blocktxn.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
const std = @import("std");
const protocol = @import("../lib.zig");

const Sha256 = std.crypto.hash.sha2.Sha256;
const BlockHeader = @import("../../../types/block_header.zig");
const Transaction = @import("../../../types/transaction.zig");
const CompactSizeUint = @import("bitcoin-primitives").types.CompatSizeUint;
const genericChecksum = @import("lib.zig").genericChecksum;
const genericDeserializeSlice = @import("lib.zig").genericDeserializeSlice;
const genericSerialize = @import("lib.zig").genericSerialize;

/// BlockTxnMessage represents the "BlockTxn" message
///
/// https://developer.bitcoin.org/reference/p2p_networking.html#blocktxn
pub const BlockTxnMessage = struct {
block_hash: [32]u8,
transactions: []Transaction,

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.transactions);
}

/// 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.transactions.len);
try indexes_count.encodeToWriter(w);
for (self.transactions) |*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());
}

/// Returns the hint of the serialized length of the message.
pub fn hintSerializedLen(self: *const Self) usize {
// 32 bytes for the block hash
const fixed_length = 32;

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

var compact_indexes_length: usize = 0;
for (self.transactions) |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 Transaction.deserializeReader(allocator, r);
blocktxn_message.transactions = try allocator.alloc(Transaction, indexes_count.value());
errdefer allocator.free(blocktxn_message.transactions);

for (blocktxn_message.transactions) |*index| {
index.* = try Transaction.deserializeReader(allocator, r);
}

return blocktxn_message;
}

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

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

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

defer msg.deinit(test_allocator);

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

const deserialized = try BlockTxnMessage.genericDeserializeSlice(test_allocator, serialized);
Copy link
Contributor

Choose a reason for hiding this comment

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

you have to use deserialize from BlockTxnMessage not the generic one

defer deserialized.deinit(test_allocator);

try std.testing.expectEqual(msg.block_hash, deserialized.block_hash);
try std.testing.expectEqual(msg.transaction[0].value(), msg.transaction[0].value());
try std.testing.expectEqual(msg.hintSerializedLen(), 32 + 1 + 1);
}
14 changes: 11 additions & 3 deletions src/network/protocol/messages/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,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 HeadersMessage = @import("headers.zig").HeadersMessage;
pub const CmpctBlockMessage = @import("cmpctblock.zig").CmpctBlockMessage;

Expand All @@ -38,12 +39,12 @@ pub const MessageTypes = enum {
notfound,
sendheaders,
filterload,
blocktxn,
getdata,
headers,
cmpctblock,
};


pub const Message = union(MessageTypes) {
version: VersionMessage,
verack: VerackMessage,
Expand All @@ -61,6 +62,7 @@ pub const Message = union(MessageTypes) {
notfound: NotFoundMessage,
sendheaders: SendHeadersMessage,
filterload: FilterLoadMessage,
blocktxn: BlockTxnMessage,
getdata: GetdataMessage,
headers: HeadersMessage,
cmpctblock: CmpctBlockMessage,
Expand All @@ -83,6 +85,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(),
.getdata => |m| @TypeOf(m).name(),
.headers => |m| @TypeOf(m).name(),
.cmpctblock => |m| @TypeOf(m).name(),
Expand All @@ -98,8 +101,11 @@ pub const Message = union(MessageTypes) {
.filteradd => |*m| m.deinit(allocator),
.getdata => |*m| m.deinit(allocator),
.cmpctblock => |*m| m.deinit(allocator),
.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),
.headers => |*m| m.deinit(allocator),
else => {}
else => {},
}
}

Expand All @@ -121,6 +127,7 @@ pub const Message = union(MessageTypes) {
.notfound => |*m| m.checksum(),
.sendheaders => |*m| m.checksum(),
.filterload => |*m| m.checksum(),
.blocktxn => |*m| m.checksum(),
.getdata => |*m| m.checksum(),
.headers => |*m| m.checksum(),
.cmpctblock => |*m| m.checksum(),
Expand All @@ -145,6 +152,7 @@ pub const Message = union(MessageTypes) {
.notfound => |m| m.hintSerializedLen(),
.sendheaders => |m| m.hintSerializedLen(),
.filterload => |*m| m.hintSerializedLen(),
.blocktxn => |*m| m.hintSerializedLen(),
.getdata => |m| m.hintSerializedLen(),
.headers => |*m| m.hintSerializedLen(),
.cmpctblock => |*m| m.hintSerializedLen(),
Expand Down Expand Up @@ -194,4 +202,4 @@ pub fn genericDeserializeSlice(comptime T: type, allocator: std.mem.Allocator, b
const reader = fbs.reader();

return try T.deserializeReader(allocator, reader);
}
}
8 changes: 8 additions & 0 deletions src/network/protocol/messages/merkleblock.zig
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,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 @@ -68,6 +72,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
42 changes: 39 additions & 3 deletions src/network/wire/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@

const std = @import("std");
const protocol = @import("../protocol/lib.zig");

const BlockHeader = @import("../../types/block_header.zig");
const CompactSizeUint = @import("bitcoin-primitives").types.CompatSizeUint;
const Sha256 = std.crypto.hash.sha2.Sha256;

pub const Error = error{
MessageTooLarge,
};

const BlockHeader = @import("../../types/block_header.zig");
/// Return the checksum of a slice
// Return the checksum of a slice
///
/// Use it on serialized messages to compute the header's value
fn computePayloadChecksum(payload: []u8) [4]u8 {
Expand Down Expand Up @@ -141,6 +141,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 if (std.mem.eql(u8, &command, protocol.messages.GetdataMessage.name()))
protocol.messages.Message{ .getdata = try protocol.messages.GetdataMessage.deserializeReader(allocator, r) }
else if (std.mem.eql(u8, &command, protocol.messages.CmpctBlockMessage.name()))
Expand Down Expand Up @@ -621,6 +623,40 @@ test "ok_send_sendcmpct_message" {
}
}

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;
const Transaction = @import("../../types/transaction.zig");

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(Transaction, 1);
indexes[0] = Transaction.init(test_allocator);
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,
}
}

test "ok_send_cmpctblock_message" {
const Transaction = @import("../../types/transaction.zig");
const OutPoint = @import("../../types/outpoint.zig");
Expand Down
Loading