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

Canonical namespace explicitly stored #426

Merged
merged 2 commits into from
Aug 12, 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
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ To be released.
- `BaseIndex.ContainsKey()` method became `abstract`. [[#390]]
- `BlockDownloadState.TotalBlockCount` and `BlockDownloadState.ReceivedBlockCount`
became to `Int64` type. [[#396], [#399]]
- Added `IStore.GetCanonicalNamespace()` method. [[#426]]
- Added `IStore.SetCanonicalNamespace()` method. [[#426]]

### Added interfaces

Expand Down Expand Up @@ -125,6 +127,7 @@ To be released.
[#417]: https://github.com/planetarium/libplanet/pull/417
[#418]: https://github.com/planetarium/libplanet/pull/418
[#424]: https://github.com/planetarium/libplanet/pull/424
[#426]: https://github.com/planetarium/libplanet/pull/426
[LiteDB #1268]: https://github.com/mbdavid/LiteDB/issues/1268


Expand Down
47 changes: 19 additions & 28 deletions Libplanet.Tests/Blockchain/BlockChainTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,25 @@ public void CanFindBlockByIndex()
Assert.Equal(anotherBlock, _blockChain[1]);
}

[Fact]
public void CanonicalId()
{
var x = _blockChain;
x.MineBlock(_fx.Address1);
x.MineBlock(_fx.Address1);
Assert.Equal(x.Id.ToString(), _fx.Store.GetCanonicalNamespace());
var y = x.Fork(x.Tip.Hash);
y.MineBlock(_fx.Address1);
Assert.Equal(x.Id.ToString(), _fx.Store.GetCanonicalNamespace());

var z = new BlockChain<DumbAction>(
new BlockPolicy<DumbAction>(new MinerReward(1)),
_fx.Store
);

Assert.Equal(x.Id, z.Id);
}

[Fact]
public void Enumerate()
{
Expand Down Expand Up @@ -1212,34 +1231,6 @@ public void MakeTransaction()
Assert.Equal(actions, transaction.Actions);
}

[Fact]
public void GetCanonicalChain()
{
Assert.Null(BlockChain<DumbAction>.GetCanonicalChain(_fx.Store));

Block<DumbAction> block1 = TestUtils.MineGenesis<DumbAction>();
Block<DumbAction> block2 = TestUtils.MineNext(block1);
Block<DumbAction> block3 = TestUtils.MineNext(block2);
Guid id1 = Guid.NewGuid();
Guid id2 = Guid.NewGuid();

foreach (Block<DumbAction> b in new[] { block1 })
{
_fx.Store.AppendIndex(id1.ToString(), b.Hash);
_fx.Store.PutBlock(b);
}

Assert.Equal(id1, BlockChain<DumbAction>.GetCanonicalChain(_fx.Store));

foreach (Block<DumbAction> b in new[] { block2, block3 })
{
_fx.Store.AppendIndex(id2.ToString(), b.Hash);
_fx.Store.PutBlock(b);
}

Assert.Equal(id2, BlockChain<DumbAction>.GetCanonicalChain(_fx.Store));
}

[Fact]
public void MineBlockWithBlockAction()
{
Expand Down
11 changes: 11 additions & 0 deletions Libplanet.Tests/Store/StoreTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,17 @@ public void DeleteNamespace()
Assert.Equal(0, Fx.Store.GetTxNonce(Fx.StoreNamespace, Fx.Transaction1.Signer));
}

[Fact]
public void CanonicalNamespace()
{
Assert.Null(Fx.Store.GetCanonicalNamespace());
Assert.Throws<ArgumentNullException>(() => Fx.Store.SetCanonicalNamespace(null));
Fx.Store.SetCanonicalNamespace("foo");
Assert.Equal("foo", Fx.Store.GetCanonicalNamespace());
Fx.Store.SetCanonicalNamespace("bar");
Assert.Equal("bar", Fx.Store.GetCanonicalNamespace());
}

[Fact]
public void ListAddresses()
{
Expand Down
12 changes: 12 additions & 0 deletions Libplanet.Tests/Store/StoreTracker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -227,5 +227,17 @@ public void UnstageTransactionIds(ISet<TxId> txids)
_logs.Add((nameof(UnstageTransactionIds), txids, null));
_store.UnstageTransactionIds(txids);
}

public string GetCanonicalNamespace()
{
_logs.Add((nameof(GetCanonicalNamespace), null, null));
return _store.GetCanonicalNamespace();
}

public void SetCanonicalNamespace(string @namespace)
{
_logs.Add((nameof(SetCanonicalNamespace), @namespace, null));
_store.SetCanonicalNamespace(@namespace);
}
}
}
39 changes: 20 additions & 19 deletions Libplanet/Blockchain/BlockChain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,20 @@ public class BlockChain<T> : IReadOnlyList<Block<T>>
private readonly object _txLock;

public BlockChain(IBlockPolicy<T> policy, IStore store)
: this(policy, store, GetCanonicalChain(store) ?? Guid.NewGuid())
: this(
policy,
store,
store.GetCanonicalNamespace()
)
{
}

internal BlockChain(IBlockPolicy<T> policy, IStore store, string @namespace)
: this(
policy,
store,
@namespace is null ? Guid.NewGuid() : Guid.Parse(@namespace)
)
{
}

Expand All @@ -43,6 +56,11 @@ internal BlockChain(IBlockPolicy<T> policy, IStore store, Guid id)

_rwlock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
_txLock = new object();

if (Store.GetCanonicalNamespace() is null)
{
Store.SetCanonicalNamespace(Id.ToString());
}
}

~BlockChain()
Expand Down Expand Up @@ -522,24 +540,6 @@ public Transaction<T> MakeTransaction(
}
}

// FIXME it should be separated into separate class (like IConsensus).
internal static Guid? GetCanonicalChain(IStore store)
{
string @namespace = store
.ListNamespaces()
.OrderByDescending(store.CountIndex)
.FirstOrDefault();

if (@namespace is null)
{
return null;
}
else
{
return new Guid(@namespace);
}
}

internal void Append(
Block<T> block,
DateTimeOffset currentTime,
Expand Down Expand Up @@ -1009,6 +1009,7 @@ t.PreviousHash is HashDigest<SHA256> tp &&

Guid obsoleteId = Id;
Id = other.Id;
Store.SetCanonicalNamespace(Id.ToString());
Blocks = new BlockSet<T>(Store);
Transactions = new TransactionSet<T>(Store);
Store.DeleteNamespace(obsoleteId.ToString());
Expand Down
6 changes: 6 additions & 0 deletions Libplanet/Store/BaseStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@ public abstract class BaseStore : IStore
/// <inheritdoc />
public abstract IEnumerable<string> ListNamespaces();

/// <inheritdoc />
public abstract string GetCanonicalNamespace();

/// <inheritdoc />
public abstract void SetCanonicalNamespace(string @namespace);

public abstract long CountIndex(string @namespace);

public abstract IEnumerable<HashDigest<SHA256>> IterateIndex(
Expand Down
37 changes: 37 additions & 0 deletions Libplanet/Store/FileStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ public string GetIndexPath(string @namespace)
);
}

public string GetCanonicalNamespacePath()
{
return Path.Combine(_path, "canon.txt");
}

public string GetStateReferencePath(string @namespace)
{
return Path.Combine(
Expand Down Expand Up @@ -182,6 +187,38 @@ public override IEnumerable<string> ListNamespaces()
}
}

/// <inheritdoc />
public override string GetCanonicalNamespace()
{
var file = new FileInfo(GetCanonicalNamespacePath());
try
{
using (StreamReader reader = file.OpenText())
{
return reader.ReadToEnd();
}
}
catch (FileNotFoundException)
{
return null;
}
}

/// <inheritdoc />
public override void SetCanonicalNamespace(string @namespace)
{
if (@namespace is null)
{
throw new ArgumentNullException(nameof(@namespace));
}

var file = new FileInfo(GetCanonicalNamespacePath());
using (StreamWriter writer = file.CreateText())
{
writer.Write(@namespace);
}
}

/// <inheritdoc/>
public override void DeleteNamespace(string @namespace)
{
Expand Down
14 changes: 14 additions & 0 deletions Libplanet/Store/IStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,20 @@ public interface IStore
/// <returns>Existing namespaces.</returns>
IEnumerable<string> ListNamespaces();

/// <summary>
/// Gets the current canonical namespace.
/// </summary>
/// <returns>The current canonical namespace. Maybe <c>null</c>.</returns>
string GetCanonicalNamespace();

/// <summary>
/// Set canonical namespace.
/// </summary>
/// <param name="namespace">A new canonical namespace. Cannot be <c>null</c>.</param>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="namespace"/> is
/// <c>null</c>.</exception>
void SetCanonicalNamespace(string @namespace);

long CountIndex(string @namespace);

/// <summary>
Expand Down
24 changes: 24 additions & 0 deletions Libplanet/Store/LiteDBStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,30 @@ public override void DeleteNamespace(string @namespace)
_db.DropCollection(StateRefId(@namespace));
}

/// <inheritdoc />
public override string GetCanonicalNamespace()
{
LiteCollection<BsonDocument> collection = _db.GetCollection<BsonDocument>("canon");
var docId = new BsonValue("canon");
BsonDocument doc = collection.FindById(docId);
return doc is null
? null
: (doc.TryGetValue("ns", out BsonValue ns) ? ns.AsString : null);
}

/// <inheritdoc />
public override void SetCanonicalNamespace(string @namespace)
{
if (@namespace is null)
{
throw new ArgumentNullException(nameof(@namespace));
}

LiteCollection<BsonDocument> collection = _db.GetCollection<BsonDocument>("canon");
var docId = new BsonValue("canon");
collection.Upsert(docId, new BsonDocument() { ["ns"] = new BsonValue(@namespace) });
}

/// <inheritdoc/>
public override long CountIndex(string @namespace)
{
Expand Down