Skip to content

Commit 3731ca4

Browse files
authoredSep 6, 2024··
Merge pull request #3949 from greymistcube/refactor/message-encoding
♻️ Changed encoding of `GetBlockHashesMsg` and `BlockHashesMsg`
2 parents 3b939e7 + e8567d3 commit 3731ca4

File tree

9 files changed

+38
-99
lines changed

9 files changed

+38
-99
lines changed
 

‎CHANGES.md

+6
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,14 @@ To be released.
2525
- (Libplanet.Net) Changed `BlockHashDownloadState` and `BlockDownloadState`
2626
to be `Obsolete`. [[#3943]]
2727
- Removed `Fork()` method from `BlockChain`. [[#3948]]
28+
- Changed the return type for `BlockChain.FindNextHashes()`
29+
to `IReadOnlyList<BlockHash>`. [[#3949]]
2830

2931
### Backward-incompatible network protocol changes
3032

33+
- (Libplanet.Net) Changed the encoding for `GetBlockHashesMsg` and
34+
`BlockHashesMsg`. [[#3949]]
35+
3136
### Backward-incompatible storage format changes
3237

3338
### Added APIs
@@ -57,6 +62,7 @@ To be released.
5762
[#3942]: https://github.com/planetarium/libplanet/pull/3942
5863
[#3943]: https://github.com/planetarium/libplanet/pull/3943
5964
[#3948]: https://github.com/planetarium/libplanet/pull/3948
65+
[#3949]: https://github.com/planetarium/libplanet/pull/3949
6066

6167

6268
Version 5.2.2

‎src/Libplanet.Net/Messages/BlockHashesMsg.cs

+3-24
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,9 @@ namespace Libplanet.Net.Messages
88
{
99
internal class BlockHashesMsg : MessageContent
1010
{
11-
public BlockHashesMsg(long? startIndex, IEnumerable<BlockHash> hashes)
11+
public BlockHashesMsg(IEnumerable<BlockHash> hashes)
1212
{
13-
StartIndex = startIndex;
1413
Hashes = hashes.ToList();
15-
16-
if (StartIndex is null == Hashes.Any())
17-
{
18-
throw new ArgumentException(
19-
"The startIndex can be null iff hashes are empty.",
20-
nameof(startIndex)
21-
);
22-
}
2314
}
2415

2516
public BlockHashesMsg(byte[][] dataFrames)
@@ -28,8 +19,7 @@ public BlockHashesMsg(byte[][] dataFrames)
2819
var hashes = new List<BlockHash>(hashCount);
2920
if (hashCount > 0)
3021
{
31-
StartIndex = BitConverter.ToInt64(dataFrames[1], 0);
32-
for (int i = 2, end = hashCount + 2; i < end; i++)
22+
for (int i = 1, end = hashCount + 1; i < end; i++)
3323
{
3424
hashes.Add(new BlockHash(dataFrames[i]));
3525
}
@@ -38,12 +28,6 @@ public BlockHashesMsg(byte[][] dataFrames)
3828
Hashes = hashes;
3929
}
4030

41-
/// <summary>
42-
/// The block index of the first hash in <see cref="Hashes"/>.
43-
/// It is <see langword="null"/> iff <see cref="Hashes"/> are empty.
44-
/// </summary>
45-
public long? StartIndex { get; }
46-
4731
/// <summary>
4832
/// The continuous block hashes, from the lowest index to the highest index.
4933
/// </summary>
@@ -58,12 +42,7 @@ public override IEnumerable<byte[]> DataFrames
5842
{
5943
var frames = new List<byte[]>();
6044
frames.Add(BitConverter.GetBytes(Hashes.Count()));
61-
if (StartIndex is { } offset)
62-
{
63-
frames.Add(BitConverter.GetBytes(offset));
64-
frames.AddRange(Hashes.Select(hash => hash.ToByteArray()));
65-
}
66-
45+
frames.AddRange(Hashes.Select(hash => hash.ToByteArray()));
6746
return frames;
6847
}
6948
}

‎src/Libplanet.Net/Messages/GetBlockHashesMsg.cs

+1-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
using System;
21
using System.Collections.Generic;
32
using Libplanet.Blockchain;
43
using Libplanet.Types.Blocks;
@@ -14,7 +13,7 @@ public GetBlockHashesMsg(BlockLocator locator)
1413

1514
public GetBlockHashesMsg(byte[][] dataFrames)
1615
{
17-
Locator = new BlockLocator(new BlockHash(dataFrames[1]));
16+
Locator = new BlockLocator(new BlockHash(dataFrames[0]));
1817
}
1918

2019
public BlockLocator Locator { get; }
@@ -26,9 +25,7 @@ public override IEnumerable<byte[]> DataFrames
2625
get
2726
{
2827
var frames = new List<byte[]>();
29-
frames.Add(BitConverter.GetBytes(1));
3028
frames.Add(Locator.Hash.ToByteArray());
31-
frames.Add(Array.Empty<byte>());
3229
return frames;
3330
}
3431
}

‎src/Libplanet.Net/Messages/MessageContent.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public enum MessageType : byte
3131
/// <summary>
3232
/// Request to query block hashes.
3333
/// </summary>
34-
GetBlockHashes = 0x04,
34+
GetBlockHashes = 0x032,
3535

3636
/// <summary>
3737
/// Inventory to transfer transactions.
@@ -76,7 +76,7 @@ public enum MessageType : byte
7676
/// <summary>
7777
/// Message containing demand block hashes with their index numbers.
7878
/// </summary>
79-
BlockHashes = 0x0e,
79+
BlockHashes = 0x33,
8080

8181
/// <summary>
8282
/// Request current chain status of the peer.

‎src/Libplanet.Net/Swarm.MessageHandlers.cs

+4-9
Original file line numberDiff line numberDiff line change
@@ -50,20 +50,15 @@ private Task ProcessMessageHandlerAsync(Message message)
5050
"Received a {MessageType} message locator [{LocatorHead}]",
5151
nameof(GetBlockHashesMsg),
5252
getBlockHashes.Locator.Hash);
53-
BlockChain.FindNextHashes(
53+
IReadOnlyList<BlockHash> hashes = BlockChain.FindNextHashes(
5454
getBlockHashes.Locator,
55-
FindNextHashesChunkSize
56-
).Deconstruct(
57-
out long? offset,
58-
out IReadOnlyList<BlockHash> hashes
59-
);
55+
FindNextHashesChunkSize);
6056
_logger.Debug(
61-
"Found {HashCount} hashes after the branchpoint (offset: {Offset}) " +
57+
"Found {HashCount} hashes after the branchpoint " +
6258
"with locator [{LocatorHead}]",
6359
hashes.Count,
64-
offset,
6560
getBlockHashes.Locator.Hash);
66-
var reply = new BlockHashesMsg(offset, hashes);
61+
var reply = new BlockHashesMsg(hashes);
6762

6863
return Transport.ReplyMessageAsync(reply, message.Identity, default);
6964
}

‎src/Libplanet/Blockchain/BlockChain.cs

+16-32
Original file line numberDiff line numberDiff line change
@@ -662,11 +662,10 @@ public IImmutableSet<TxId> GetStagedTransactionIds()
662662
/// <param name="locator">The <see cref="BlockLocator"/> to find the branching point
663663
/// from.</param>
664664
/// <param name="count">The Maximum number of <see cref="BlockHash"/>es to return.</param>
665-
/// <returns>A tuple of the index of the branch point and <see cref="BlockHash"/>es
666-
/// including the branch point <see cref="BlockHash"/>. If no branch point is found,
667-
/// returns a tuple of <see langword="null"/> and an empty array of
668-
/// <see cref="BlockHash"/>es.</returns>
669-
public Tuple<long?, IReadOnlyList<BlockHash>> FindNextHashes(
665+
/// <returns>A list of <see cref="BlockHash"/>es including
666+
/// the branch point <see cref="BlockHash"/>. If no branch point is found,
667+
/// returns an empty list of <see cref="BlockHash"/>es.</returns>
668+
public IReadOnlyList<BlockHash> FindNextHashes(
670669
BlockLocator locator,
671670
int count = 500)
672671
{
@@ -675,12 +674,12 @@ public IImmutableSet<TxId> GetStagedTransactionIds()
675674

676675
if (!(FindBranchpoint(locator) is { } branchpoint))
677676
{
678-
return new Tuple<long?, IReadOnlyList<BlockHash>>(null, Array.Empty<BlockHash>());
677+
return Array.Empty<BlockHash>();
679678
}
680679

681680
if (!(Store.GetBlockIndex(branchpoint) is { } branchpointIndex))
682681
{
683-
return new Tuple<long?, IReadOnlyList<BlockHash>>(null, Array.Empty<BlockHash>());
682+
return Array.Empty<BlockHash>();
684683
}
685684

686685
var result = new List<BlockHash>();
@@ -705,7 +704,7 @@ public IImmutableSet<TxId> GetStagedTransactionIds()
705704
Store.ListChainIds().Count(),
706705
stopwatch.ElapsedMilliseconds);
707706

708-
return new Tuple<long?, IReadOnlyList<BlockHash>>(branchpointIndex, result);
707+
return result;
709708
}
710709

711710
/// <summary>
@@ -1190,34 +1189,19 @@ internal void AppendStateRootHashPreceded(
11901189
/// <see langword="null"/>.</returns>
11911190
internal BlockHash? FindBranchpoint(BlockLocator locator)
11921191
{
1193-
try
1192+
if (ContainsBlock(locator.Hash))
11941193
{
1195-
_rwlock.EnterReadLock();
1196-
1197-
_logger.Debug(
1198-
"Finding a branchpoint with locator [{LocatorHead}]",
1199-
locator.Hash);
1200-
BlockHash hash = locator.Hash;
1201-
if (_blocks.ContainsKey(hash)
1202-
&& _blocks[hash] is Block block
1203-
&& hash.Equals(Store.IndexBlockHash(Id, block.Index)))
1204-
{
1205-
_logger.Debug(
1206-
"Found a branchpoint with locator [{LocatorHead}]: {Hash}",
1207-
locator.Hash,
1208-
hash);
1209-
return hash;
1210-
}
1211-
12121194
_logger.Debug(
1213-
"Failed to find a branchpoint locator [{LocatorHead}]",
1195+
"Found a branchpoint with locator [{LocatorHead}]: {Hash}",
1196+
locator.Hash,
12141197
locator.Hash);
1215-
return null;
1216-
}
1217-
finally
1218-
{
1219-
_rwlock.ExitReadLock();
1198+
return locator.Hash;
12201199
}
1200+
1201+
_logger.Debug(
1202+
"Failed to find a branchpoint locator [{LocatorHead}]",
1203+
locator.Hash);
1204+
return null;
12211205
}
12221206

12231207
/// <summary>

‎test/Libplanet.Net.Tests/Messages/BlockHashesTest.cs

+1-14
Original file line numberDiff line numberDiff line change
@@ -19,23 +19,11 @@ public void Dispose()
1919
NetMQConfig.Cleanup(false);
2020
}
2121

22-
[Fact]
23-
public void Constructor()
24-
{
25-
Assert.Throws<ArgumentException>(() =>
26-
new BlockHashesMsg(null, new[] { default(BlockHash) })
27-
);
28-
Assert.Throws<ArgumentException>(() =>
29-
new BlockHashesMsg(123, new BlockHash[0])
30-
);
31-
}
32-
3322
[Fact]
3423
public void Decode()
3524
{
3625
BlockHash[] blockHashes = GenerateRandomBlockHashes(100L).ToArray();
37-
var msg = new BlockHashesMsg(123, blockHashes);
38-
Assert.Equal(123, msg.StartIndex);
26+
var msg = new BlockHashesMsg(blockHashes);
3927
Assert.Equal(blockHashes, msg.Hashes);
4028
var privateKey = new PrivateKey();
4129
AppProtocolVersion apv = AppProtocolVersion.Sign(privateKey, 3);
@@ -48,7 +36,6 @@ public void Decode()
4836
peer,
4937
DateTimeOffset.UtcNow);
5038
BlockHashesMsg restored = (BlockHashesMsg)messageCodec.Decode(encoded, true).Content;
51-
Assert.Equal(msg.StartIndex, restored.StartIndex);
5239
Assert.Equal(msg.Hashes, restored.Hashes);
5340
}
5441

‎test/Libplanet.Net.Tests/Messages/NetMQMessageCodecTest.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ private MessageContent CreateMessage(MessageContent.MessageType type)
119119
case MessageContent.MessageType.BlockHeaderMessage:
120120
return new BlockHeaderMsg(genesis.Hash, genesis.Header);
121121
case MessageContent.MessageType.BlockHashes:
122-
return new BlockHashesMsg(0, new[] { genesis.Hash });
122+
return new BlockHashesMsg(new[] { genesis.Hash });
123123
case MessageContent.MessageType.GetChainStatus:
124124
return new GetChainStatusMsg();
125125
case MessageContent.MessageType.ChainStatus:

‎test/Libplanet.Tests/Blockchain/BlockChainTest.cs

+4-13
Original file line numberDiff line numberDiff line change
@@ -433,12 +433,9 @@ public void RenderActionsAfterAppendComplete()
433433
public void FindNextHashes()
434434
{
435435
var key = new PrivateKey();
436-
long? offsetIndex;
437436
IReadOnlyList<BlockHash> hashes;
438437

439-
_blockChain.FindNextHashes(
440-
new BlockLocator(_blockChain.Genesis.Hash))
441-
.Deconstruct(out offsetIndex, out hashes);
438+
hashes = _blockChain.FindNextHashes(new BlockLocator(_blockChain.Genesis.Hash));
442439
Assert.Single(hashes);
443440
Assert.Equal(_blockChain.Genesis.Hash, hashes.First());
444441
var block0 = _blockChain.Genesis;
@@ -451,19 +448,13 @@ public void FindNextHashes()
451448
key, lastCommit: CreateBlockCommit(_blockChain.Tip));
452449
_blockChain.Append(block3, CreateBlockCommit(block3));
453450

454-
_blockChain.FindNextHashes(new BlockLocator(block0.Hash))
455-
.Deconstruct(out offsetIndex, out hashes);
456-
Assert.Equal(0, offsetIndex);
451+
hashes = _blockChain.FindNextHashes(new BlockLocator(block0.Hash));
457452
Assert.Equal(new[] { block0.Hash, block1.Hash, block2.Hash, block3.Hash }, hashes);
458453

459-
_blockChain.FindNextHashes(new BlockLocator(block1.Hash))
460-
.Deconstruct(out offsetIndex, out hashes);
461-
Assert.Equal(1, offsetIndex);
454+
hashes = _blockChain.FindNextHashes(new BlockLocator(block1.Hash));
462455
Assert.Equal(new[] { block1.Hash, block2.Hash, block3.Hash }, hashes);
463456

464-
_blockChain.FindNextHashes(new BlockLocator(block0.Hash), count: 2)
465-
.Deconstruct(out offsetIndex, out hashes);
466-
Assert.Equal(0, offsetIndex);
457+
hashes = _blockChain.FindNextHashes(new BlockLocator(block0.Hash), count: 2);
467458
Assert.Equal(new[] { block0.Hash, block1.Hash }, hashes);
468459
}
469460

0 commit comments

Comments
 (0)
Please sign in to comment.