2021-05-18 21:01:10 +00:00
|
|
|
package kit
|
2020-08-13 20:37:09 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"sync/atomic"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
|
2020-09-07 03:49:10 +00:00
|
|
|
"github.com/filecoin-project/go-state-types/abi"
|
2020-08-13 20:37:09 +00:00
|
|
|
"github.com/filecoin-project/lotus/miner"
|
|
|
|
)
|
|
|
|
|
2021-05-19 09:51:32 +00:00
|
|
|
// BlockMiner is a utility that makes a test miner Mine blocks on a timer.
|
2020-08-13 20:37:09 +00:00
|
|
|
type BlockMiner struct {
|
2021-05-19 09:51:32 +00:00
|
|
|
t *testing.T
|
|
|
|
miner TestStorageNode
|
|
|
|
|
|
|
|
nextNulls int64
|
|
|
|
stopCh chan chan struct{}
|
2020-08-13 20:37:09 +00:00
|
|
|
}
|
|
|
|
|
2021-05-19 09:51:32 +00:00
|
|
|
func NewBlockMiner(t *testing.T, miner TestStorageNode) *BlockMiner {
|
2020-08-13 20:37:09 +00:00
|
|
|
return &BlockMiner{
|
2021-05-19 09:51:32 +00:00
|
|
|
t: t,
|
|
|
|
miner: miner,
|
|
|
|
stopCh: make(chan chan struct{}),
|
2020-08-13 20:37:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-05-19 09:51:32 +00:00
|
|
|
func (bm *BlockMiner) MineBlocks(ctx context.Context, blocktime time.Duration) {
|
2020-08-13 20:37:09 +00:00
|
|
|
time.Sleep(time.Second)
|
2021-05-19 09:51:32 +00:00
|
|
|
|
2020-08-13 20:37:09 +00:00
|
|
|
go func() {
|
2021-05-19 09:51:32 +00:00
|
|
|
for {
|
2020-11-12 15:23:46 +00:00
|
|
|
select {
|
2021-05-19 09:51:32 +00:00
|
|
|
case <-time.After(blocktime):
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
case ch := <-bm.stopCh:
|
|
|
|
close(ch)
|
|
|
|
close(bm.stopCh)
|
2020-11-12 15:23:46 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2021-05-19 09:51:32 +00:00
|
|
|
nulls := atomic.SwapInt64(&bm.nextNulls, 0)
|
|
|
|
if err := bm.miner.MineOne(ctx, miner.MineReq{
|
2020-08-13 20:37:09 +00:00
|
|
|
InjectNulls: abi.ChainEpoch(nulls),
|
2020-08-27 00:51:16 +00:00
|
|
|
Done: func(bool, abi.ChainEpoch, error) {},
|
2020-08-13 20:37:09 +00:00
|
|
|
}); err != nil {
|
|
|
|
bm.t.Error(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
|
2021-05-19 09:51:32 +00:00
|
|
|
// InjectNulls injects the specified amount of null rounds in the next
|
|
|
|
// mining rounds.
|
|
|
|
func (bm *BlockMiner) InjectNulls(rounds abi.ChainEpoch) {
|
|
|
|
atomic.AddInt64(&bm.nextNulls, int64(rounds))
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stop stops the block miner.
|
2020-08-13 20:37:09 +00:00
|
|
|
func (bm *BlockMiner) Stop() {
|
2021-05-19 09:51:32 +00:00
|
|
|
bm.t.Log("shutting down mining")
|
|
|
|
if _, ok := <-bm.stopCh; ok {
|
|
|
|
// already stopped
|
|
|
|
return
|
|
|
|
}
|
|
|
|
ch := make(chan struct{})
|
|
|
|
bm.stopCh <- ch
|
|
|
|
<-ch
|
2020-08-13 20:37:09 +00:00
|
|
|
}
|