Skip to content

Commit

Permalink
Remove obsolete stuff from the test framework
Browse files Browse the repository at this point in the history
  • Loading branch information
NicolasDorier committed Apr 7, 2018
1 parent 54d4826 commit a7d1606
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 204 deletions.
163 changes: 6 additions & 157 deletions NBitcoin.TestFramework/NodeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -526,88 +526,20 @@ private void FindPorts(int[] ports)
}
}

List<Transaction> transactions = new List<Transaction>();
HashSet<OutPoint> locked = new HashSet<OutPoint>();
Money fee = Money.Coins(0.0001m);
public Transaction GiveMoney(Script destination, Money amount, bool broadcast = true)
public uint256[] Generate(int blockCount)
{
var rpc = CreateRPCClient();
TransactionBuilder builder = new TransactionBuilder();
builder.AddKeys(rpc.ListSecrets().OfType<ISecret>().ToArray());
builder.AddCoins(rpc.ListUnspent().Where(c => !locked.Contains(c.OutPoint)).Select(c => c.AsCoin()));
builder.Send(destination, amount);
builder.SendFees(fee);
builder.SetChange(GetFirstSecret(rpc));
var tx = builder.BuildTransaction(true);
foreach(var outpoint in tx.Inputs.Select(i => i.PrevOut))
{
locked.Add(outpoint);
}
if(broadcast)
Broadcast(tx);
else
transactions.Add(tx);
return tx;
return CreateRPCClient().Generate(blockCount);
}

public void Rollback(Transaction tx)
{
transactions.Remove(tx);
foreach(var outpoint in tx.Inputs.Select(i => i.PrevOut))
{
locked.Remove(outpoint);
}

}

#if !NOSOCKET
public void Broadcast(Transaction transaction)
{
using(var node = CreateNodeClient())
{
node.VersionHandshake();
node.SendMessageAsync(new InvPayload(transaction));
node.SendMessageAsync(new TxPayload(transaction));
node.PingPong();
}
}
#else
public void Broadcast(Transaction transaction)
{
var rpc = CreateRPCClient();
rpc.SendRawTransaction(transaction);
}
#endif
public void SelectMempoolTransactions()
public void Broadcast(params Transaction[] transactions)
{
var rpc = CreateRPCClient();
var txs = rpc.GetRawMempool();
var tasks = txs.Select(t => rpc.GetRawTransactionAsync(t)).ToArray();
Task.WaitAll(tasks);
transactions.AddRange(tasks.Select(t => t.Result).ToArray());
}

public void Broadcast(Transaction[] transactions)
{
var batch = rpc.PrepareBatch();
foreach(var tx in transactions)
Broadcast(tx);
}

public void Split(Money amount, int parts)
{
var rpc = CreateRPCClient();
TransactionBuilder builder = new TransactionBuilder();
builder.AddKeys(rpc.ListSecrets().OfType<ISecret>().ToArray());
builder.AddCoins(rpc.ListUnspent().Select(c => c.AsCoin()));
var secret = GetFirstSecret(rpc);
foreach(var part in (amount - fee).Split(parts))
{
builder.Send(secret, part);
batch.SendRawTransactionAsync(tx);
}
builder.SendFees(fee);
builder.SetChange(secret);
var tx = builder.BuildTransaction(true);
Broadcast(tx);
rpc.SendBatch();
}

object l = new object();
Expand All @@ -634,18 +566,6 @@ public void WaitForExit()
}
}

public DateTimeOffset? MockTime
{
get;
set;
}

public void SetMinerSecret(BitcoinSecret secret)
{
CreateRPCClient().ImportPrivKey(secret);
MinerSecret = secret;
}

public BitcoinSecret MinerSecret
{
get;
Expand All @@ -658,77 +578,6 @@ public bool CookieAuth
set;
} = true;

public Block[] Generate(int blockCount, bool includeUnbroadcasted = true, bool broadcast = true)
{
var rpc = CreateRPCClient();
BitcoinSecret dest = GetFirstSecret(rpc);
var bestBlock = rpc.GetBestBlockHash();
ConcurrentChain chain = null;
List<Block> blocks = new List<Block>();
DateTimeOffset now = MockTime == null ? DateTimeOffset.UtcNow : MockTime.Value;
#if !NOSOCKET
using(var node = CreateNodeClient())
{

node.VersionHandshake();
chain = bestBlock == node.Network.GenesisHash ? new ConcurrentChain(node.Network) : node.GetChain();
for(int i = 0; i < blockCount; i++)
{
uint nonce = 0;
Block block = Network.Consensus.ConsensusFactory.CreateBlock();
block.Header.HashPrevBlock = chain.Tip.HashBlock;
block.Header.Bits = block.Header.GetWorkRequired(rpc.Network, chain.Tip);
block.Header.UpdateTime(now, rpc.Network, chain.Tip);
var coinbase = new Transaction();
coinbase.AddInput(TxIn.CreateCoinbase(chain.Height + 1));
coinbase.AddOutput(new TxOut(rpc.Network.GetReward(chain.Height + 1), dest.GetAddress()));
block.AddTransaction(coinbase);
if(includeUnbroadcasted)
{
transactions = Reorder(transactions);
block.Transactions.AddRange(transactions);
transactions.Clear();
}
block.UpdateMerkleRoot();
while(!block.CheckProofOfWork())
block.Header.Nonce = ++nonce;
blocks.Add(block);
chain.SetTip(block.Header);
}
if(broadcast)
BroadcastBlocks(blocks.ToArray(), node);
}
return blocks.ToArray();
#endif
}

public void BroadcastBlocks(Block[] blocks)
{
using(var node = CreateNodeClient())
{
node.VersionHandshake();
BroadcastBlocks(blocks, node);
}
}

public void BroadcastBlocks(Block[] blocks, Node node)
{
Block lastSent = null;
foreach(var block in blocks)
{
node.SendMessageAsync(new InvPayload(block));
node.SendMessageAsync(new BlockPayload(block));
lastSent = block;
}
node.PingPong();
}

public Block[] FindBlock(int blockCount = 1, bool includeMempool = true)
{
SelectMempoolTransactions();
return Generate(blockCount, includeMempool);
}

class TransactionNode
{
public TransactionNode(Transaction tx)
Expand Down
4 changes: 2 additions & 2 deletions NBitcoin.Tests/AltcoinTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public void CanSyncWithPoW()
{
var node = builder.CreateNode();
builder.StartAll();
node.CreateRPCClient().Generate(100);
node.Generate(100);

var nodeClient = node.CreateNodeClient();
nodeClient.VersionHandshake();
Expand All @@ -60,7 +60,7 @@ public void CanSyncWithoutPoW()
{
var node = builder.CreateNode();
builder.StartAll();
node.CreateRPCClient().Generate(100);
node.Generate(100);
var nodeClient = node.CreateNodeClient();
nodeClient.VersionHandshake();
ConcurrentChain chain = new ConcurrentChain(builder.Network);
Expand Down
71 changes: 38 additions & 33 deletions NBitcoin.Tests/ProtocolTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,29 +237,30 @@ public void CanGetMerkleRoot()
{
using(var builder = NodeBuilderEx.Create())
{
var node = builder.CreateNode(true).CreateNodeClient();
builder.Nodes[0].Generate(101);
var rpc = builder.Nodes[0].CreateRPCClient();
builder.Nodes[0].Split(Money.Coins(50m), 50);
builder.Nodes[0].SelectMempoolTransactions();
builder.Nodes[0].Generate(1);
var node = builder.CreateNode(true);
var rpc = node.CreateRPCClient();
var nodeClient = node.CreateNodeClient();
rpc.Generate(101);
var batch = rpc.PrepareBatch();
for(int i = 0; i < 20; i++)
{
rpc.SendToAddress(new Key().PubKey.GetAddress(rpc.Network), Money.Coins(0.5m));
#pragma warning disable CS4014
batch.SendToAddressAsync(new Key().PubKey.GetAddress(rpc.Network), Money.Coins(0.5m));
#pragma warning restore CS4014
}
builder.Nodes[0].SelectMempoolTransactions();
builder.Nodes[0].Generate(1);
var block = builder.Nodes[0].CreateRPCClient().GetBlock(103);
var knownTx = block.Transactions[0].GetHash();
var knownAddress = block.Transactions[0].Outputs[0].ScriptPubKey.GetDestination();
node.VersionHandshake();
using(var list = node.CreateListener()
batch.SendBatch();
var blockId = rpc.Generate(1)[0];
var block = rpc.GetBlock(blockId);
var knownTx = block.Transactions[1].GetHash();
var knownAddress = block.Transactions[1].Outputs[0].ScriptPubKey.GetDestination();
nodeClient.VersionHandshake();
using(var list = nodeClient.CreateListener()
.Where(m => m.Message.Payload is MerkleBlockPayload || m.Message.Payload is TxPayload))
{
BloomFilter filter = new BloomFilter(1, 0.005, 50, BloomFlags.UPDATE_NONE);
filter.Insert(knownAddress.ToBytes());
node.SendMessageAsync(new FilterLoadPayload(filter));
node.SendMessageAsync(new GetDataPayload(new InventoryVector(InventoryType.MSG_FILTERED_BLOCK, block.GetHash())));
nodeClient.SendMessageAsync(new FilterLoadPayload(filter));
nodeClient.SendMessageAsync(new GetDataPayload(new InventoryVector(InventoryType.MSG_FILTERED_BLOCK, block.GetHash())));
var merkle = list.ReceivePayload<MerkleBlockPayload>();
var tree = merkle.Object.PartialMerkleTree;
Assert.True(tree.Check(block.Header.HashMerkleRoot));
Expand Down Expand Up @@ -288,7 +289,7 @@ public void CanGetMerkleRoot()
act();

var unknownBlock = uint256.Parse("00000000ad262227291eaf90cafdc56a8f8451e2d7653843122c5bb0bf2dfcdd");
node.SendMessageAsync(new GetDataPayload(new InventoryVector(InventoryType.MSG_FILTERED_BLOCK, Network.RegTest.GetGenesis().GetHash())));
nodeClient.SendMessageAsync(new GetDataPayload(new InventoryVector(InventoryType.MSG_FILTERED_BLOCK, Network.RegTest.GetGenesis().GetHash())));

merkle = list.ReceivePayload<MerkleBlockPayload>();
tree = merkle.Object.PartialMerkleTree;
Expand Down Expand Up @@ -334,7 +335,7 @@ public void CanMaintainChainWithChainBehavior()
using(var builder = NodeBuilderEx.Create())
{
var node = builder.CreateNode(true).CreateNodeClient();
builder.Nodes[0].CreateRPCClient().Generate(600);
builder.Nodes[0].Generate(600);
var rpc = builder.Nodes[0].CreateRPCClient();
var chain = node.GetChain(rpc.GetBlockHash(500));
Assert.True(chain.Height == 500);
Expand Down Expand Up @@ -399,8 +400,9 @@ public void CanGetTransactionsFromMemPool()
var node = builder.CreateNode();
node.ConfigParameters.Add("whitelist", "127.0.0.1");
node.Start();
node.Generate(101);
node.CreateRPCClient().SendToAddress(new Key().PubKey.GetAddress(Network.RegTest), Money.Coins(1.0m));
var rpc = node.CreateRPCClient();
rpc.Generate(101);
rpc.SendToAddress(new Key().PubKey.GetAddress(Network.RegTest), Money.Coins(1.0m));
var client = node.CreateNodeClient();
client.VersionHandshake();
var transactions = client.GetMempoolTransactions();
Expand Down Expand Up @@ -451,7 +453,8 @@ public void CanGetBlocksWithProtocol()
using(var builder = NodeBuilderEx.Create())
{
var node = builder.CreateNode(true);
node.Generate(50);
var rpc = node.CreateRPCClient();
rpc.Generate(50);
var client = node.CreateNodeClient();
var chain = client.GetChain();
var blocks = client.GetBlocks(chain.GetBlock(20).HashBlock).ToArray();
Expand All @@ -472,9 +475,10 @@ public void CanGetMemPool()
using(var builder = NodeBuilderEx.Create())
{
var node = builder.CreateNode();
var rpc = node.CreateRPCClient();
node.ConfigParameters.Add("whitelist", "127.0.0.1");
node.Start();
node.Generate(102);
rpc.Generate(102);
for(int i = 0; i < 2; i++)
node.CreateRPCClient().SendToAddress(new Key().PubKey.GetAddress(Network.RegTest), Money.Coins(1.0m));
var client = node.CreateNodeClient();
Expand All @@ -491,13 +495,13 @@ public void SynchronizeChainSurviveReorg()
{
ConcurrentChain chain = new ConcurrentChain(Network.RegTest);
var node1 = builder.CreateNode(true);
node1.CreateRPCClient().Generate(10);
node1.Generate(10);
node1.CreateNodeClient().SynchronizeChain(chain);
Assert.Equal(10, chain.Height);


var node2 = builder.CreateNode(true);
node2.CreateRPCClient().Generate(12);
node2.Generate(12);

var node2c = node2.CreateNodeClient();
node2c.PollHeaderDelay = TimeSpan.FromSeconds(2);
Expand All @@ -513,37 +517,38 @@ public void CanGetChainsConcurrenty()
using(var builder = NodeBuilderEx.Create())
{
bool generating = true;
builder.CreateNode(true);
var node = builder.CreateNode(true);
var rpc = node.CreateRPCClient();
Task.Run(() =>
{
builder.Nodes[0].Generate(600);
rpc.Generate(600);
generating = false;
});
var node = builder.Nodes[0].CreateNodeClient();
node.PollHeaderDelay = TimeSpan.FromSeconds(2);
node.VersionHandshake();
var nodeClient = node.CreateNodeClient();
nodeClient.PollHeaderDelay = TimeSpan.FromSeconds(2);
nodeClient.VersionHandshake();
Random rand = new Random();
Thread.Sleep(1000);
var chains =
Enumerable.Range(0, 5)
.Select(_ => Task.Factory.StartNew(() =>
{
Thread.Sleep(rand.Next(0, 1000));
return node.GetChain();
return nodeClient.GetChain();
}))
.Select(t => t.Result)
.ToArray();
while(generating)
{
SyncAll(node, rand, chains);
SyncAll(nodeClient, rand, chains);
}
SyncAll(node, rand, chains);
SyncAll(nodeClient, rand, chains);
foreach(var c in chains)
{
Assert.Equal(600, c.Height);
}

var chainNoHeader = node.GetChain(new SynchronizeChainOptions() { SkipPoWCheck = true, StripHeaders = true });
var chainNoHeader = nodeClient.GetChain(new SynchronizeChainOptions() { SkipPoWCheck = true, StripHeaders = true });
Assert.False(chainNoHeader.Tip.HasHeader);
}
}
Expand Down
Loading

0 comments on commit a7d1606

Please sign in to comment.