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

notfound #137

Merged
merged 11 commits into from
Sep 30, 2024
Merged
12 changes: 12 additions & 0 deletions src/network/protocol/messages/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ pub const MerkleBlockMessage = @import("merkleblock.zig").MerkleBlockMessage;
pub const FeeFilterMessage = @import("feefilter.zig").FeeFilterMessage;
pub const SendCmpctMessage = @import("sendcmpct.zig").SendCmpctMessage;
pub const FilterClearMessage = @import("filterclear.zig").FilterClearMessage;
pub const NotFoundMessage = @import("notfound.zig").NotFoundMessage;

pub const InventoryVector = struct {
type: u32,
hash: [32]u8,
};

pub const MessageTypes = enum {
version,
Expand All @@ -23,6 +29,7 @@ pub const MessageTypes = enum {
sendcmpct,
feefilter,
filterclear,
notfound,
};

pub const Message = union(MessageTypes) {
Expand All @@ -37,6 +44,7 @@ pub const Message = union(MessageTypes) {
sendcmpct: SendCmpctMessage,
feefilter: FeeFilterMessage,
filterclear: FilterClearMessage,
notfound: NotFoundMessage,

pub fn name(self: Message) *const [12]u8 {
return switch (self) {
Expand All @@ -51,6 +59,7 @@ pub const Message = union(MessageTypes) {
.sendcmpct => |m| @TypeOf(m).name(),
.feefilter => |m| @TypeOf(m).name(),
.filterclear => |m| @TypeOf(m).name(),
.notfound => |m| @TypeOf(m).name(),
};
}

Expand All @@ -67,6 +76,7 @@ pub const Message = union(MessageTypes) {
.sendcmpct => {},
.feefilter => {},
.filterclear => {},
.notfound => {},
}
}

Expand All @@ -83,6 +93,7 @@ pub const Message = union(MessageTypes) {
.sendcmpct => |m| m.checksum(),
.feefilter => |m| m.checksum(),
.filterclear => |m| m.checksum(),
.notfound => |m| m.checksum(),
};
}

Expand All @@ -99,6 +110,7 @@ pub const Message = union(MessageTypes) {
.sendcmpct => |m| m.hintSerializedLen(),
.feefilter => |m| m.hintSerializedLen(),
.filterclear => |m| m.hintSerializedLen(),
.notfound => |m| m.hintSerializedLen(),
};
}
};
127 changes: 127 additions & 0 deletions src/network/protocol/messages/notfound.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
const std = @import("std");
const protocol = @import("../lib.zig");
const Sha256 = std.crypto.hash.sha2.Sha256;
const InventoryVector = @import("lib.zig").InventoryVector;

/// NotFoundMessage represents the "notfound" message
///
/// https://developer.bitcoin.org/reference/p2p_networking.html#notfound
pub const NotFoundMessage = struct {
inventory: []const InventoryVector,

const Self = @This();

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

/// Returns the message checksum
///
/// Computed as `Sha256(Sha256(self.serialize()))[0..4]`
pub fn checksum(self: *const Self) [4]u8 {
var digest: [32]u8 = undefined;
var hasher = Sha256.init(.{});
const writer = hasher.writer();
self.serializeToWriter(writer) catch unreachable; // Sha256.write is infallible
hasher.final(&digest);

Sha256.hash(&digest, &digest, .{});

return digest[0..4].*;
}

/// 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 the message as bytes and write them to the Writer.
pub fn serializeToWriter(self: *const Self, writer: anytype) !void {
try writer.writeInt(u32, @intCast(self.inventory.len), .little);
for (self.inventory) |inv| {
try writer.writeInt(u32, inv.type, .little);
try writer.writeAll(&inv.hash);
}
tdelabro marked this conversation as resolved.
Show resolved Hide resolved
}

/// Serialize a message as bytes and return them.
pub fn serialize(self: *const Self, allocator: std.mem.Allocator) ![]u8 {
const serialized_len = self.hintSerializedLen();

const ret = try allocator.alloc(u8, serialized_len);
errdefer allocator.free(ret);

try self.serializeToSlice(ret);

return ret;
}

/// Deserialize a Reader bytes as a `NotFoundMessage`
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'.");
}

const count = try r.readInt(u32, .little);
const inventory = try allocator.alloc(InventoryVector, count);
errdefer allocator.free(inventory);

for (inventory) |*inv| {
inv.type = try r.readInt(u32, .little);
try r.readNoEof(&inv.hash);
}

return Self{
.inventory = inventory,
};
}

/// Deserialize bytes into a `NotFoundMessage`
pub fn deserializeSlice(allocator: std.mem.Allocator, bytes: []const u8) !Self {
var fbs = std.io.fixedBufferStream(bytes);
const reader = fbs.reader();

return try Self.deserializeReader(allocator, reader);
}

pub fn hintSerializedLen(self: *const Self) usize {
return 4 + self.inventory.len * (4 + 32); // count (4 bytes) + (type (4 bytes) + hash (32 bytes)) * count
}

pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
allocator.free(self.inventory);
}

pub fn new(inventory: []const InventoryVector) Self {
return .{
.inventory = inventory,
};
}
};

// TESTS
// TESTS
test "ok_fullflow_notfound_message" {
const allocator = std.testing.allocator;

{
const inventory = [_]InventoryVector{
.{ .type = 1, .hash = [_]u8{0xab} ** 32 },
.{ .type = 2, .hash = [_]u8{0xcd} ** 32 },
};
var msg = NotFoundMessage.new(&inventory);
const payload = try msg.serialize(allocator);
defer allocator.free(payload);
var deserialized_msg = try NotFoundMessage.deserializeSlice(allocator, payload);
defer deserialized_msg.deinit(allocator);

try std.testing.expectEqual(msg.inventory.len, deserialized_msg.inventory.len);
for (msg.inventory, deserialized_msg.inventory) |orig, deserialized| {
try std.testing.expectEqual(orig.type, deserialized.type);
try std.testing.expectEqualSlices(u8, &orig.hash, &deserialized.hash);
}
}
}
4 changes: 4 additions & 0 deletions src/network/wire/lib.zig
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@ pub fn receiveMessage(
protocol.messages.Message{ .sendcmpct = try protocol.messages.SendCmpctMessage.deserializeReader(allocator, r) }
else if (std.mem.eql(u8, &command, protocol.messages.FilterClearMessage.name()))
protocol.messages.Message{ .filterclear = try protocol.messages.FilterClearMessage.deserializeReader(allocator, r) }
else if (std.mem.eql(u8, &command, protocol.messages.NotFoundMessage.name()))
protocol.messages.Message{ .notfound = try protocol.messages.NotFoundMessage.deserializeReader(allocator, r) }
else if (std.mem.eql(u8, &command, protocol.messages.FeeFilterMessage.name()))
protocol.messages.Message{ .feefilter = try protocol.messages.FeeFilterMessage.deserializeReader(allocator, r) }
else {
try r.skipBytes(payload_len, .{}); // Purge the wire
return error.UnknownMessage;
Expand Down
Loading