Skip to content

Commit

Permalink
Merge pull request #3455 from greymistcube/feature/ibencodable-hashdi…
Browse files Browse the repository at this point in the history
…gest

✨ `IBencodable` `HashDigest<T>`
  • Loading branch information
OnedgeLee authored Oct 27, 2023
2 parents a5937c2 + 5a4765d commit bcf5c78
Show file tree
Hide file tree
Showing 6 changed files with 53 additions and 27 deletions.
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ To be released.

### Backward-incompatible API changes

- Added `IBencodable` interface to `HashDigest<T>`. [[#3455]]

### Backward-incompatible network protocol changes

### Backward-incompatible storage format changes
Expand All @@ -27,6 +29,7 @@ To be released.
### CLI tools

[#3454]: https://github.com/planetarium/libplanet/pull/3454
[#3455]: https://github.com/planetarium/libplanet/pull/3455


Version 3.6.0
Expand Down
22 changes: 21 additions & 1 deletion Libplanet.Common/HashDigest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using Bencodex;
using Bencodex.Types;
using Libplanet.Common.Serialization;

namespace Libplanet.Common
Expand All @@ -36,7 +38,7 @@ namespace Libplanet.Common
[TypeConverter(typeof(HashDigestTypeConverter))]
[JsonConverter(typeof(HashDigestJsonConverter))]
[Serializable]
public readonly struct HashDigest<T> : ISerializable, IEquatable<HashDigest<T>>
public readonly struct HashDigest<T> : ISerializable, IEquatable<HashDigest<T>>, IBencodable
where T : HashAlgorithm
{
/// <summary>
Expand Down Expand Up @@ -114,6 +116,21 @@ public HashDigest(in ImmutableArray<byte> hashDigest)
_byteArray = hashDigest;
}

public HashDigest(IValue bencoded)
: this(bencoded is Binary binary
? binary
: throw new ArgumentException(
$"Given {nameof(bencoded)} must be of type " +
$"{typeof(Binary)}: {bencoded.GetType()}",
nameof(bencoded)))
{
}

private HashDigest(Binary binary)
: this(binary.ByteArray)
{
}

private HashDigest(
SerializationInfo info,
StreamingContext context)
Expand All @@ -130,6 +147,9 @@ private HashDigest(
public ImmutableArray<byte> ByteArray =>
_byteArray.IsDefault ? DefaultByteArray : _byteArray;

/// <inheritdoc cref="IBencodable.Bencoded"/>
public IValue Bencoded => new Binary(ByteArray);

/// <summary>
/// Converts a given hexadecimal representation of a digest into
/// a <see cref="HashDigest{T}"/> object.
Expand Down
7 changes: 4 additions & 3 deletions Libplanet.Common/Libplanet.Common.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<PackageId>Libplanet.Common</PackageId>
<Title>Libplanet.Common</Title>
Expand All @@ -18,7 +18,7 @@
<IsTestProject>false</IsTestProject>
<CodeAnalysisRuleSet>..\Libplanet.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="System.Collections.Immutable" Version="1.*" />
<PackageReference Include="System.Text.Json" Version="6.0.*" />
Expand All @@ -34,6 +34,7 @@
runtime; build; native; contentfiles; analyzers; buildtransitive
</IncludeAssets>
</PackageReference>
<PackageReference Include="Bencodex" Version="0.14.0" />
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.205">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>
Expand All @@ -42,5 +43,5 @@
</PackageReference>
<AdditionalFiles Include="..\stylecop.json" />
</ItemGroup>

</Project>
17 changes: 13 additions & 4 deletions Libplanet.Tests/HashDigestTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,20 @@ public void DefaultConstructor()
public void DisallowNull()
{
Assert.Throws<ArgumentNullException>(
() => new HashDigest<SHA1>(null)
);
() => new HashDigest<SHA1>((byte[])null));
Assert.Throws<ArgumentNullException>(
() => new HashDigest<SHA256>(null)
);
() => new HashDigest<SHA256>((byte[])null));
}

[Fact]
public void Bencoded()
{
Assert.NotEqual(HashDigest<SHA1>.Size, HashDigest<SHA256>.Size);
var digest = new HashDigest<SHA256>(TestUtils.GetRandomBytes(HashDigest<SHA256>.Size));
var bencoded = digest.Bencoded;
var decoded = new HashDigest<SHA256>(bencoded);
Assert.Equal(digest, decoded);
Assert.Throws<ArgumentOutOfRangeException>(() => new HashDigest<SHA1>(bencoded));
}

[Fact]
Expand Down
27 changes: 10 additions & 17 deletions Libplanet.Types/Blocks/BlockMarshaler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public static Dictionary MarshalBlockMetadata(IBlockMetadata metadata)

if (metadata.TxHash is { } th)
{
dict = dict.Add(TxHashKey, th.ByteArray);
dict = dict.Add(TxHashKey, th.Bencoded);
}

dict = metadata.PublicKey is { } pubKey
Expand All @@ -109,13 +109,7 @@ HashDigest<SHA256> preEvaluationHash
)
{
Dictionary dict = marshaledMetadata;
ImmutableArray<byte> preEvaluationHashBytes = preEvaluationHash.ByteArray;

if (!preEvaluationHashBytes.IsDefaultOrEmpty)
{
dict = dict.Add(PreEvaluationHashKey, preEvaluationHashBytes);
}

dict = dict.Add(PreEvaluationHashKey, preEvaluationHash.Bencoded);
return dict;
}

Expand All @@ -135,8 +129,8 @@ BlockHash hash
)
{
Dictionary dict = marshaledPreEvaluatedBlockHeader
.Add(StateRootHashKey, stateRootHash.ByteArray)
.Add(HashKey, hash.ByteArray);
.Add(StateRootHashKey, stateRootHash.Bencoded)
.Add(HashKey, hash.Bencoded);
if (signature is { } sig)
{
dict = dict.Add(SignatureKey, sig);
Expand Down Expand Up @@ -207,11 +201,11 @@ public static BlockMetadata UnmarshalBlockMetadata(Dictionary marshaled)
CultureInfo.InvariantCulture),
miner: miner,
publicKey: publicKey,
previousHash: marshaled.ContainsKey(PreviousHashKey)
? new BlockHash(marshaled[PreviousHashKey])
previousHash: marshaled.TryGetValue(PreviousHashKey, out IValue phv)
? new BlockHash(phv)
: (BlockHash?)null,
txHash: marshaled.ContainsKey(TxHashKey)
? new HashDigest<SHA256>(((Binary)marshaled[TxHashKey]).ByteArray)
txHash: marshaled.TryGetValue(TxHashKey, out IValue thv)
? new HashDigest<SHA256>(thv)
: (HashDigest<SHA256>?)null,
lastCommit: marshaled.ContainsKey(LastCommitKey)
? new BlockCommit(marshaled[LastCommitKey])
Expand All @@ -220,7 +214,7 @@ public static BlockMetadata UnmarshalBlockMetadata(Dictionary marshaled)
}

public static HashDigest<SHA256> UnmarshalPreEvaluationHash(Dictionary marshaled) =>
new HashDigest<SHA256>(((Binary)marshaled[PreEvaluationHashKey]).ByteArray);
new HashDigest<SHA256>(marshaled[PreEvaluationHashKey]);

public static PreEvaluationBlockHeader UnmarshalPreEvaluationBlockHeader(
Dictionary marshaled)
Expand All @@ -242,8 +236,7 @@ public static BlockHash UnmarshalBlockHeaderHash(Dictionary marshaledBlockHeader
public static HashDigest<SHA256> UnmarshalBlockHeaderStateRootHash(
Dictionary marshaledBlockHeader
) =>
new HashDigest<SHA256>(
((Binary)marshaledBlockHeader[StateRootHashKey]).ByteArray);
new HashDigest<SHA256>(marshaledBlockHeader[StateRootHashKey]);

public static ImmutableArray<byte>? UnmarshalBlockHeaderSignature(
Dictionary marshaledBlockHeader
Expand Down
4 changes: 2 additions & 2 deletions Libplanet.Types/Tx/TxExecution.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,12 +197,12 @@ public IValue ToBencodex()

if (InputState is { } inputState)
{
dict = dict.Add(InputStateKey, inputState.ByteArray);
dict = dict.Add(InputStateKey, inputState.Bencoded);
}

if (OutputState is { } outputState)
{
dict = dict.Add(OutputStateKey, outputState.ByteArray);
dict = dict.Add(OutputStateKey, outputState.Bencoded);
}

if (ExceptionNames is { } exceptionNames)
Expand Down

0 comments on commit bcf5c78

Please sign in to comment.