Skip to content

Commit

Permalink
Merge pull request #1141 from limebell/bugfix/cancel-mineblock
Browse files Browse the repository at this point in the history
Register WatchTip at beggining of MineBlock
  • Loading branch information
limebell authored Jan 5, 2021
2 parents dbd5734 + b1f86e6 commit e44d148
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ To be released.

### Bug fixes

- Fixed a bug where `BlockChain<T>.MineBlock()` was not automatically
cancelled when the tip of the chain was changed occasionally. [[#1141]]

### CLI tools

- `planet mpt diff` command became to take 4 arguments (which was 3)
Expand Down Expand Up @@ -140,6 +143,7 @@ To be released.
[#1132]: https://github.com/planetarium/libplanet/pull/1132
[#1135]: https://github.com/planetarium/libplanet/pull/1135
[#1136]: https://github.com/planetarium/libplanet/pull/1136
[#1141]: https://github.com/planetarium/libplanet/pull/1141


Version 0.10.2
Expand Down
15 changes: 7 additions & 8 deletions Libplanet/Blockchain/BlockChain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,12 @@ public async Task<Block<T>> MineBlock(
CancellationToken cancellationToken = default(CancellationToken)
)
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationTokenSource cancellationTokenSource =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token);
void WatchTip(object target, (Block<T> OldTip, Block<T> NewTip) tip) => cts.Cancel();
TipChanged += WatchTip;

maxTransactions = Math.Max(
Math.Min(
maxTransactions ?? Policy.MaxTransactionsPerBlock,
Expand Down Expand Up @@ -874,13 +880,6 @@ public async Task<Block<T>> MineBlock(
stagedTransactions.Length
);

CancellationTokenSource cts = new CancellationTokenSource();
CancellationTokenSource cancellationTokenSource =
CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token);

void WatchTip(object target, (Block<T> OldTip, Block<T> NewTip) tip) => cts.Cancel();
TipChanged += WatchTip;

Block<T> block;
try
{
Expand All @@ -902,7 +901,7 @@ public async Task<Block<T>> MineBlock(
if (cts.IsCancellationRequested)
{
throw new OperationCanceledException(
"Mining canceled due to change of tip index");
"Mining canceled due to change of tip index.");
}

throw new OperationCanceledException(cancellationToken);
Expand Down

0 comments on commit e44d148

Please sign in to comment.