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

Make Swarm's direct access code to store atomic #363

Merged
merged 5 commits into from
Jul 23, 2019
Merged
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
5 changes: 5 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ To be released.
a feasible user interface so that they can decide whom to trust
for themselves.
[[#272], [#343]]
- Added `StoreExtension.ListAllStateReferences(this IStore, string)` extension
method. [[#363]]
- `Address` class became to implement `IComparable<Address>` and
`IComparable` interfaces. [[#363]]

### Behavioral changes

Expand All @@ -42,6 +46,7 @@ To be released.

[#343]: https://github.com/planetarium/libplanet/pull/343
[#350]: https://github.com/planetarium/libplanet/pull/350
[#363]: https://github.com/planetarium/libplanet/pull/363
[#365]: https://github.com/planetarium/libplanet/pull/365
[#366]: https://github.com/planetarium/libplanet/pull/366

Expand Down
35 changes: 35 additions & 0 deletions Libplanet.Tests/AddressTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using Libplanet.Crypto;
using Xunit;
Expand Down Expand Up @@ -221,5 +222,39 @@ public void CanSerializeAndDeserialize()

Assert.Equal(deserializedAddress, expectedAddress);
}

[Fact]
public void Compare()
{
var random = new System.Random();
var buffer = new byte[20];
Address[] addresses = Enumerable.Repeat(0, 50).Select(_ =>
{
random.NextBytes(buffer);
return new Address(buffer);
}).ToArray();
for (int i = 1; i < addresses.Length; i++)
{
IComparable<Address> left = addresses[i - 1];
Address right = addresses[i];
string leftString = addresses[i - 1].ToHex().ToLower(),
rightString = right.ToHex().ToLower();
Assert.Equal(
Math.Min(Math.Max(left.CompareTo(right), 1), -1),
Math.Min(Math.Max(leftString.CompareTo(rightString), 1), -1)
);
Assert.Equal(
left.CompareTo(right),
(left as IComparable).CompareTo(right)
);
}

Assert.Throws<ArgumentNullException>(() =>
(addresses[0] as IComparable).CompareTo(null)
);
Assert.Throws<ArgumentException>(() =>
(addresses[0] as IComparable).CompareTo("invalid")
);
}
}
}
63 changes: 40 additions & 23 deletions Libplanet.Tests/Blockchain/BlockChainTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,19 +263,25 @@ public void Append()
DumbAction.RenderRecords.Value =
ImmutableList<DumbAction.RenderRecord>.Empty;

(Address[] addresses, Block<DumbAction>[] blocks) = MakeFixturesForAppendTests();
(
IImmutableDictionary<Address, object> expectedStates,
Block<DumbAction>[] blocks
) = MakeFixturesForAppendTests();
Address[] addresses = expectedStates.Keys.ToArray();

Assert.Empty(_blockChain.Blocks);
try
{
_blockChain.Append(blocks[0]);
Assert.Contains(blocks[0], _blockChain);
Assert.Equal(new[] { blocks[0] }, _blockChain.ToArray());
Assert.NotNull(_blockChain.Store.GetBlockStates(blocks[0].Hash));
Assert.Empty(DumbAction.RenderRecords.Value);

_blockChain.Append(blocks[1]);
Assert.Contains(blocks[1], _blockChain);
Assert.Equal(blocks, _blockChain.ToArray());
Assert.NotNull(_blockChain.Store.GetBlockStates(blocks[1].Hash));
var renders = DumbAction.RenderRecords.Value;
Assert.Equal(4, renders.Count);
Assert.True(renders.All(r => r.Render));
Expand Down Expand Up @@ -316,7 +322,7 @@ public void Append()
addresses.Select(renders[3].Context.PreviousStates.GetState)
);
Assert.Equal(
new[] { "foo", "bar", "baz", "qux" },
expectedStates.Values,
addresses.Select(renders[3].NextStates.GetState)
);
}
Expand All @@ -332,7 +338,7 @@ public void AppendWithoutEvaluateActions()
{
DumbAction.RenderRecords.Value = ImmutableList<DumbAction.RenderRecord>.Empty;

(Address[] addresses, Block<DumbAction>[] blocks) = MakeFixturesForAppendTests();
(_, Block<DumbAction>[] blocks) = MakeFixturesForAppendTests();

try
{
Expand Down Expand Up @@ -374,6 +380,25 @@ public void AppendValidatesBlock()
() => blockChain.Append(_fx.Block1));
}

[Fact]
public void ExecuteActions()
{
(var expectedStates, Block<DumbAction>[] blocks) = MakeFixturesForAppendTests();
_blockChain.Append(blocks[0]);
_blockChain.Append(
blocks[1],
DateTimeOffset.UtcNow,
evaluateActions: false,
renderActions: false
);

_blockChain.ExecuteActions(blocks[1], true);
Assert.Equal(
expectedStates.ToImmutableDictionary(),
_blockChain.Store.GetBlockStates(blocks[1].Hash)
);
}

[Fact]
public void FindNextHashes()
{
Expand Down Expand Up @@ -627,7 +652,8 @@ public void CanGetBlockLocator()
[InlineData(false)]
public void Swap(bool render)
{
(Address[] addresses, Block<DumbAction>[] blocks) = MakeFixturesForAppendTests();
(var expectedStates, Block<DumbAction>[] blocks) = MakeFixturesForAppendTests();
Address[] addresses = expectedStates.Keys.ToArray();
foreach (Block<DumbAction> block in blocks)
{
_blockChain.Append(block);
Expand Down Expand Up @@ -1267,10 +1293,12 @@ void BuildIndex(Guid id, Block<DumbAction> block)
return (signer, addresses, chain);
}

private (Address[] addresses, Block<DumbAction>[]) MakeFixturesForAppendTests()
private (ImmutableSortedDictionary<Address, object>, Block<DumbAction>[])
MakeFixturesForAppendTests()
{
Address[] addresses = Enumerable.Repeat(0, 4)
.Select(_ => new PrivateKey().PublicKey.ToAddress())
.OrderBy(a => a)
.ToArray();
Block<DumbAction> b0 = TestUtils.MineGenesis<DumbAction>();

Expand All @@ -1296,25 +1324,14 @@ void BuildIndex(Guid id, Block<DumbAction> block)
)
);

return (addresses, new[] { b0, b1 });
}

private sealed class NullPolicy<T> : IBlockPolicy<T>
where T : IAction, new()
{
private readonly InvalidBlockException _exceptionToThrow;

public NullPolicy(InvalidBlockException exceptionToThrow = null)
var expectedStates = new SortedDictionary<Address, object>
{
_exceptionToThrow = exceptionToThrow;
}

public long GetNextBlockDifficulty(IReadOnlyList<Block<T>> blocks) =>
blocks.Any() ? 1 : 0;

public InvalidBlockException ValidateNextBlock(
IReadOnlyList<Block<T>> blocks, Block<T> nextBlock) =>
_exceptionToThrow;
{ addresses[0], "foo" },
{ addresses[1], "bar" },
{ addresses[2], "baz" },
{ addresses[3], "qux" },
};
return (expectedStates.ToImmutableSortedDictionary(), new[] { b0, b1 });
}

private sealed class TestEvaluateAction : IAction
Expand Down
26 changes: 26 additions & 0 deletions Libplanet.Tests/Blockchain/NullPolicy.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using System.Collections.Generic;
using System.Linq;
using Libplanet.Action;
using Libplanet.Blockchain.Policies;
using Libplanet.Blocks;

namespace Libplanet.Tests.Blockchain
{
public sealed class NullPolicy<T> : IBlockPolicy<T>
where T : IAction, new()
{
private readonly InvalidBlockException _exceptionToThrow;

public NullPolicy(InvalidBlockException exceptionToThrow = null)
{
_exceptionToThrow = exceptionToThrow;
}

public long GetNextBlockDifficulty(IReadOnlyList<Block<T>> blocks) =>
blocks.Any() ? 1 : 0;

public InvalidBlockException ValidateNextBlock(
IReadOnlyList<Block<T>> blocks, Block<T> nextBlock) =>
_exceptionToThrow;
}
}
53 changes: 53 additions & 0 deletions Libplanet.Tests/Store/StoreExtensionTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Security.Cryptography;
using Libplanet.Blockchain;
using Libplanet.Blocks;
using Libplanet.Crypto;
using Libplanet.Tests.Blockchain;
using Libplanet.Tests.Common.Action;
using Libplanet.Tx;
using Xunit;
Expand Down Expand Up @@ -74,5 +79,53 @@ public void LookupStateReference(StoreFixture fx)
fx.Store.LookupStateReference(fx.StoreNamespace, address, block6)
);
}

[Theory]
[MemberData(nameof(StoreFixtures))]
public void ListAllStateReferences(StoreFixture fx)
{
Address address1 = fx.Address1;
Address address2 = fx.Address2;
Address address3 = new PrivateKey().PublicKey.ToAddress();

Transaction<DumbAction> tx4 = fx.MakeTransaction(
new[]
{
new DumbAction(address1, "foo1"),
new DumbAction(address2, "foo2"),
}
);
Block<DumbAction> block4 = TestUtils.MineNext(fx.Block3, new[] { tx4 });

Transaction<DumbAction> tx5 = fx.MakeTransaction(
new[]
{
new DumbAction(address1, "bar1"),
new DumbAction(address3, "bar3"),
}
);
Block<DumbAction> block5 = TestUtils.MineNext(block4, new[] { tx5 });

Block<DumbAction> block6 = TestUtils.MineNext(block5, new Transaction<DumbAction>[0]);

var chain = new BlockChain<DumbAction>(new NullPolicy<DumbAction>(), fx.Store);
chain.Append(fx.Block1);
chain.Append(fx.Block2);
chain.Append(fx.Block3);
chain.Append(block4);
chain.Append(block5);
chain.Append(block6);

IImmutableDictionary<Address, IImmutableList<HashDigest<SHA256>>> refs =
fx.Store.ListAllStateReferences(chain.Id.ToString());

Assert.Equal(
new HashSet<Address> { address1, address2, address3 },
refs.Keys.ToHashSet()
);
Assert.Equal(new[] { block4.Hash, block5.Hash }, refs[address1]);
Assert.Equal(new[] { block4.Hash }, refs[address2]);
Assert.Equal(new[] { block5.Hash }, refs[address3]);
}
}
}
34 changes: 33 additions & 1 deletion Libplanet/Address.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
Expand Down Expand Up @@ -39,7 +40,7 @@ namespace Libplanet
/// <seealso cref="PublicKey"/>
[Serializable]
[Equals]
public struct Address : ISerializable
public struct Address : ISerializable, IComparable<Address>, IComparable
{
/// <summary>
/// The <see cref="byte"/>s size that each <see cref="Address"/> takes.
Expand Down Expand Up @@ -210,6 +211,37 @@ public void GetObjectData(
info.AddValue("address", _byteArray.ToArray());
}

int IComparable<Address>.CompareTo(Address other)
{
ImmutableArray<byte> self = ByteArray, operand = other.ByteArray;

for (int i = 0; i < Size; i++)
{
int cmp = ((IComparable<byte>)self[i]).CompareTo(operand[i]);
if (cmp != 0)
{
return cmp;
}
}

return 0;
}

int IComparable.CompareTo(object obj)
{
if (obj is Address other)
{
return ((IComparable<Address>)this).CompareTo(other);
}

if (obj is null)
{
throw new ArgumentNullException(nameof(obj));
}

throw new ArgumentException(nameof(obj));
}

private static string ToChecksumAddress(string hex)
{
byte[] bytes = Encoding.ASCII.GetBytes(hex);
Expand Down
Loading