static void Main(string[] args) { ITransaction txn5 = SetupTransactions(); IKeyStore keyStore = new KeyStore(Hmac.GenerateKey()); int levelOfDifficult = 3; IBlock <ClaimSettlement> block1 = new Block(0, keyStore, levelOfDifficult); IBlock <ClaimSettlement> block2 = new Block(1, keyStore, levelOfDifficult); IBlock <ClaimSettlement> block3 = new Block(2, keyStore, levelOfDifficult); IBlock <ClaimSettlement> block4 = new Block(3, keyStore, levelOfDifficult); AddTransactionsToBlocksAndCalculateHashes(block1, block2, block3, block4); var chain = new BlockChain <ClaimSettlement>(); chain.Add(block1); chain.Add(block2); chain.Add(block3); chain.Add(block4); if (chain.Verify()) { Console.WriteLine("chain verified"); } else { Console.WriteLine("chain verification failed"); } }
public void GivenBlockChain_AppendTwoNode_ShouldVerify() { var now = DateTime.Now; var principleSignature = new PrincipleSignature("issuer", "audience", TimeSpan.FromMinutes(1), new RsaPublicPrivateKey()); var blockChain = new BlockChain(); var block1 = new DataBlock <TextBlock>(now, "blockTypeV1", "blockIdV1", new TextBlock("name", "type", "author", "dataV1")); block1 = block1.WithSignature(principleSignature); blockChain.Add(block1); block1.Validate(_workContext, principleSignature); var block2 = new DataBlock <TextBlock>(now, "blockTypeV2", "blockIdV2", new TextBlock("name", "type", "author", "dataV2")); block2 = block2.WithSignature(principleSignature); blockChain.Add(block2); block2.Validate(_workContext, principleSignature); blockChain.IsValid().Should().BeTrue(); IPrincipleSignatureContainer keyContainer = new PrincipleSignatureContainer() { principleSignature, }; blockChain.Validate(_workContext, keyContainer); }
public void ReceiveCoins() { // Quick check that we can actually receive coins. var tx1 = TestUtils.CreateFakeTx(_unitTestParams, Utils.ToNanoCoins(1, 0), _wallet.Keychain[0].ToAddress(_unitTestParams)); var b1 = TestUtils.CreateFakeBlock(_unitTestParams, _blockStore, tx1).Block; _chain.Add(b1); Assert.IsTrue(_wallet.GetBalance().CompareTo(0UL) > 0); }
public void GivenBlockChain_AppendTwoNode_ShouldVerify() { var now = DateTimeOffset.Now; var blockChain = new BlockChain(); var block1 = new DataBlock <TextBlock>(now, "blockTypeV1", "blockIdV1", new TextBlock("name", "type", "author", "dataV1")); blockChain.Add(block1); var block2 = new DataBlock <TextBlock>(now, "blockTypeV2", "blockIdV2", new TextBlock("name", "type", "author", "dataV2")); blockChain.Add(block2); blockChain.IsValid().Should().BeTrue(); }
public void AddAndReadTest() { if (System.IO.File.Exists(File2)) { System.IO.File.Delete(File2); } if (System.IO.File.Exists($"{File2}.h")) { System.IO.File.Delete($"{File2}.h"); } var blockChain = new BlockChain <TestBlockData>(File2); using var sha256 = SHA256.Create(); TestBlockData data = new TestBlockData("12345678910"); var prevBlock = blockChain.First(); var block = Block <TestBlockData> .Create(prevBlock.Hash(sha256), data, prevBlock.GetBlockHeader().GetTarget(), sha256); var token = new CancellationTokenSource(); token.CancelAfter(TimeSpan.FromSeconds(TimeoutInSec)); var m = block.Mine(token.Token); m.Wait(); block = m.Result; blockChain.Add(block); Assert.IsTrue(TestHelper.ArrayEquals(block.ToArray(), blockChain.First().ToArray()), "Block is not added to the blockchain, or could not read the blockchain"); Assert.IsTrue(blockChain.First().IsValid(prevBlock.Hash(sha256), sha256), "Added block is not valid"); }
public async Task FindNonce() { await Task.Run(() => { lock (lockObject_) { ulong nonce = 0; do { NewBlock.Nonce = nonce; var hash = GetHash(NewBlock); if (hash < Target) { BlockChain.Add(NewBlock); NewBlock = null; LastHash = SerializeHash(hash); OnBlockChainChanged(); TransactionPool.Clear(); OnTransactionPoolChanged(); return; } ++nonce; } while (nonce != ulong.MaxValue); throw new Exception("nonce not found."); } }); }
public void GivenBlockChain_AppendSingleNode_ShouldVerify() { var now = DateTime.Now; var principleSignature = new PrincipleSignature("bobTheIssuer", "bobCustomer", TimeSpan.FromMinutes(1), new RsaPublicPrivateKey()); var blockChain = new BlockChain(); var block1 = new DataBlock <TextBlock>(now, "blockTypeV1", "blockIdV1", new TextBlock("name", "type", "author", "dataV1")); block1.Validate(); string block1Digest = block1.Digest; block1 = block1.WithSignature(principleSignature); blockChain.Add(block1); block1.Validate(); block1Digest.Should().Be(block1.Digest); block1.Validate(_workContext, principleSignature); blockChain.IsValid().Should().BeTrue(); IPrincipleSignatureContainer keyContainer = new PrincipleSignatureContainer() { principleSignature, }; blockChain.Validate(_workContext, keyContainer); }
static void TestBlockChain(Block <TestBlockData> validBlock) { const string file = "blochweakdb2.feeawbasfewa"; Console.WriteLine($"--------------------- BlockChain2 --------------------------"); using var sha256 = SHA256.Create(); var blockChain = new BlockChain <TestBlockData>(file, sha256); var sw = Stopwatch.StartNew(); for (int i = 0; i < count; i++) { blockChain.Add(validBlock); } Console.WriteLine($"Write({count}): {sw.ElapsedMilliseconds}"); sw.Restart(); var _ = blockChain.Count(); Console.WriteLine($"Read({_}): {sw.ElapsedMilliseconds}"); sw.Restart(); byte[] timestamp = new byte[] { 17, 104, 230, 94, 127, 183, 215, 8 }; var __ = blockChain.Count(x => ArrayEquals(x.GetBlockHeader().Time, timestamp)); Console.WriteLine($"Search({_}): {sw.ElapsedMilliseconds}"); sw.Restart(); Console.WriteLine($"FileSize f1: {new FileInfo(file).Length}"); Console.WriteLine($"FileSize f2: {new FileInfo(file+".h").Length}"); }
private void HandleDailyDealEligibility(DailyDealEligibilityModel eligibility) { _logger.LogInformation("Received new eligibility"); var watch = Stopwatch.StartNew(); _eligibilityRepository.Create(eligibility); var tId = $"{eligibility.GamingSystemId}-{eligibility.ProductId}-{eligibility.UserId}"; IBlockChain transaction = new BlockChain(INSESSION_TRANSACTION_NAME, tId); IBlock lastBlock = transaction.GetLastBlock(); IBlock currentBlock = new Block(lastBlock.Index, "Daily_Deal_Created_v1", eligibility.ToJson(), watch.Elapsed, lastBlock.Hash); transaction.Add(currentBlock); if (transaction.IsValid()) { var insessTransaction = new TransactionMessage.Insession(transaction); PubishTransction(insessTransaction); var conversion = new ConversionModel() { Amount = 250, GamingSystemId = eligibility.GamingSystemId, ProductId = eligibility.ProductId, UserId = eligibility.UserId }; Context.System.Scheduler.ScheduleTellOnce(TimeSpan.FromSeconds(10), Self, conversion, Self); } }
public void TestBlockChainNewBlock() { var data = Enumerable.Range(0, 256).Select(x => (byte)random.Next()); chain.Add(new Block(data.ToArray())); Assert.AreEqual(2, chain.Items.Count); }
public void TestBasicChaining() { // Check that we can plug a few blocks together. // Block 1 from the testnet. var b1 = GetBlock1(); Assert.True(_testNetChain.Add(b1)); // Block 2 from the testnet. var b2 = GetBlock2(); // Let's try adding an invalid block. var n = b2.Nonce; try { b2.Nonce = 12345; _testNetChain.Add(b2); Assert.Fail(); } catch (VerificationException) { b2.Nonce = n; } // Now it works because we reset the nonce. Assert.True(_testNetChain.Add(b2)); }
public void Should_add_new_block_and_stay_valid() { var blockChain = new BlockChain <TestData>(2); var data = new TestData("ABC1234", 2020); blockChain.Add(new Block(DateTime.UtcNow, data)); blockChain.Chain.Last().Data.Should().Be.EqualTo(data); blockChain.IsValid().Should().Be.True(); }
public static void ProcessPendingTransactions(this BlockChain blocks, string minerAddress) { IBlock block = new Block(blocks.LastOrDefault().Hash, blocks.PendingTransactions); blocks.Add(block); blocks.PendingTransactions = new List <Transaction>(); blocks.CreateTransaction(new Transaction(null, minerAddress, blocks.Reward)); }
public void Should_be_invalid_if_blocks_chain_is_corrupted() { var blockChain = new BlockChain <TestData>(2); var data1 = new TestData("AAA000", 2020); var data2 = new TestData("AAA001", 2020); var block1 = new Block(DateTime.UtcNow, data1); var block2 = new Block(DateTime.UtcNow, data2); blockChain.Add(block1); blockChain.Add(block2); var newChain = new List <Block> { block2, block1 }; blockChain.ForceSet(newChain); blockChain.IsValid().Should().Be.False(); }
public void Should_mine_block_when_adding_it_and_match_the_difficulty_provided() { var difficulty = 3; var blockChain = new BlockChain <TestData>(difficulty); var block = new Block(DateTime.UtcNow, new TestData("123", 2020)); blockChain.Add(block); block.Hash.Substring(0, difficulty).Should().Be.EqualTo("000"); }
public Chain(Block block) { if (block == null) { throw new InvalidBlockException("Блок провайдера данных не может быть равным null."); } var b = new Block(block.Hash, block.PreviousHash, block.TimeStamp, block.Index, block.MerkleRoot, block.CurrentTransactions); BlockChain.Add(b); }
public void Should_be_invalid_if_block_data_is_corrupted() { var blockChain = new BlockChain <TestData>(2); var data = new TestData("ABC1234", 2020); blockChain.Add(new Block(DateTime.UtcNow, data)); (blockChain.Chain.Last().Data as TestData).Year = 2019; blockChain.IsValid().Should().Be.False(); }
/// <summary> /// Получить данные из локальной цепочки. /// </summary> /// <param name="localChain"> Локальная цепочка блоков. </param> protected void LoadDataFromLocalChain(Chain localChain) { if (localChain == null) { throw new InvalidBlockException("Локальная цепочка блоков не может быть равна null."); } foreach (var block in localChain.blockChain) { BlockChain.Add(block); } }
public Chain(List <Block> blocks) { if (blocks == null) { throw new InvalidBlockException("Список блоков провайдера данных не может быть равным null."); } foreach (var block in blocks) { var b = new Block(block.Hash, block.PreviousHash, block.TimeStamp, block.Index, block.MerkleRoot, block.CurrentTransactions); BlockChain.Add(b); } }
public async Task VerifyTest() { if (System.IO.File.Exists(File)) { System.IO.File.Delete(File); } if (System.IO.File.Exists($"{File}.h")) { System.IO.File.Delete($"{File}.h"); } var blockChain = new BlockChain <TestBlockData>(File); var data = new[] { new TestBlockData("12345678910"), new TestBlockData("12345678911230"), new TestBlockData("123455678910"), new TestBlockData("1234567891120") }; var token = new CancellationTokenSource(); token.CancelAfter(TimeSpan.FromSeconds(TimeoutInSec)); foreach (var d in data) { await blockChain.Add(d, token : token.Token); } //Check blockchain var x = await blockChain.Verify(token.Token); Assert.IsTrue(x, "Valid blockchain was marked invalid"); //Make blockchain invalid MakeBlockChainInvalid(); foreach (var d in data) { await blockChain.Add(d, token : token.Token); //Add some random blocks } //Check blockchain again x = await blockChain.Verify(token.Token); Assert.IsFalse(x, "Invalid blockchain was marked valid"); }
public void GivenBlockChain_AppendManyNode_ShouldVerify() { var now = DateTimeOffset.Now; const int max = 10; var blockChain = new BlockChain(); List <DataBlock <TextBlock> > list = Enumerable.Range(0, max) .Select(x => new DataBlock <TextBlock>(now, $"blockTypeV{x}", $"blockIdV{x}", new TextBlock("name", "type", "author", $"dataV{x}"))) .ToList(); blockChain.Add(list.ToArray()); blockChain.IsValid().Should().BeTrue(); }
public void TestSetBlockHash() { //Arrange var txn1 = new ClaimSettlement("ABC123", 1000.00m, DateTime.Now, "QWE123", 10000, ClaimType.TotalLoss); var txn2 = new ClaimSettlement("ABC123", 1000.00m, DateTime.Now, "QWE123", 10000, ClaimType.TotalLoss); IBlock <ClaimSettlement> block = new Block(0, 3); IBlockChain <ClaimSettlement> blockChain = new BlockChain <ClaimSettlement>(); //Act block.Add(txn1); block.Add(txn2); blockChain.Add(block); //Assert Assert.AreEqual(32, block.BlockHash.Length); }
public void AddTest() { if (System.IO.File.Exists(File)) { System.IO.File.Delete(File); } var blockChain = new BlockChain <TestBlockData>(File); var data = new TestBlockData("12345678910"); var token = new CancellationTokenSource(); token.CancelAfter(TimeSpan.FromSeconds(TimeoutInSec)); blockChain.Add(data, token: token.Token).Wait(); Assert.IsTrue(TestHelper.ArrayEquals(data.ToArray(), blockChain.First().GetData().ToArray()), "Block is not added to the blockchain, or could not read the blockchain"); Assert.IsTrue(blockChain.First().IsValid(blockChain.First().GetBlockHeader().HashPrevBlock, blockChain.GetHashingAlgorithm()), "Added block is not valid"); }
private void ReplaceLocalChainFromGlobalChain(Chain localChain, Chain globalChain) { if (globalChain == null || localChain == null) { throw new InvalidBlockException("Глобальная цепочка блоков не может быть равна null."); } var countNewBlocks = globalChain.Length - localChain.Length; // blockSubscriber.Clear(); var newBlocks = globalChain.BlockChain.AsEnumerable().Reverse().Take(countNewBlocks).ToList(); foreach (var block in newBlocks) { BlockChain.Add(block); } }
static void Main(string[] args) { var blockchain = new BlockChain <StringData>(2); Console.WriteLine("Welcome to blockchain console!"); while (true) { Console.WriteLine("Write new block value: "); var value = Console.ReadLine(); blockchain.Add(new Block(DateTime.Now, new StringData(value))); Console.WriteLine("Block added!"); Console.WriteLine($"Blockchain is {(blockchain.IsValid() ? "valid" : "invalid")}"); Console.WriteLine(JsonConvert.SerializeObject(blockchain.Chain, Formatting.Indented)); } }
static void Main(string[] args) { Random rnd = new Random(DateTime.UtcNow.Millisecond); IBlock genesis = new Block(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00 }); byte[] difficulty = new byte[] { 0x00, 0x00 }; BlockChain chain = new BlockChain(difficulty, genesis); for (int i = 0; i < 200; i++) { var data = Enumerable.Range(0, 2256).Select(p => (byte)rnd.Next()); chain.Add(new Block(data.ToArray())); Console.WriteLine(chain.LastOrDefault()?.ToString()); Console.WriteLine($"Chain is valid: {chain.IsValid()}"); } Console.ReadLine(); }
public void GivenBlockChain_WhenSerialized_ShouldRoundTrip() { var blockChain = new BlockChain(); var block1 = new DataBlock <TextBlock>(DateTime.Now, "blockTypeV1", "blockIdV1", new TextBlock("name", "type", "author", "dataV1")); blockChain.Add(block1); blockChain.IsValid().Should().BeTrue(); string blockChainHash = blockChain.ToMerkleTree().BuildTree().ToString(); string json = blockChain.ToJson(); BlockChain result = json.ToBlockChain(); result.Blocks.Count.Should().Be(blockChain.Blocks.Count); blockChain.IsValid().Should().BeTrue(); string resultChainHash = result.ToMerkleTree().BuildTree().ToString(); blockChainHash.Should().Be(resultChainHash); }
public void TestUnconnectedBlocks() { var b1 = _unitTestParams.GenesisBlock.CreateNextBlock(_coinbaseTo); var b2 = b1.CreateNextBlock(_coinbaseTo); var b3 = b2.CreateNextBlock(_coinbaseTo); // Connected. Assert.True(_chain.Add(b1)); // Unconnected but stored. The head of the chain is still b1. Assert.False(_chain.Add(b3)); Assert.AreEqual(_chain.ChainHead.Header, b1.CloneAsHeader()); // Add in the middle block. Assert.True(_chain.Add(b2)); Assert.AreEqual(_chain.ChainHead.Header, b3.CloneAsHeader()); }
public void GivenBlockChain_AppendManyNode_ShouldVerify() { var now = DateTime.Now; const int max = 10; var principleSignature = new PrincipleSignature("issuer", "audience", TimeSpan.FromMinutes(1), new RsaPublicPrivateKey()); var blockChain = new BlockChain(); List <DataBlock <TextBlock> > list = Enumerable.Range(0, max) .Select(x => new DataBlock <TextBlock>(now, $"blockTypeV{x}", $"blockIdV{x}", new TextBlock("name", "type", "author", $"dataV{x}")).WithSignature(principleSignature)) .ToList(); blockChain.Add(list.ToArray()); blockChain.IsValid().Should().BeTrue(); IPrincipleSignatureContainer keyContainer = new PrincipleSignatureContainer() { principleSignature, }; blockChain.Validate(_workContext, keyContainer); }
public void GivenBlockChain_AppendManyNode_ShouldVerify() { var now = DateTime.Now; const int max = 10; var blockChain = new BlockChain(); List <DataBlock <TextBlock> > list = Enumerable.Range(0, max) .Select(x => new DataBlock <TextBlock>(now, $"blockTypeV{x}", $"blockIdV{x}", new TextBlock("name", "type", "author", $"dataV{x}"))) .ToList(); blockChain.Add(list.ToArray()); blockChain.IsValid().Should().BeTrue(); string blockChainHash = blockChain.ToMerkleTree().BuildTree().ToString(); string json = blockChain.ToJson(); BlockChain result = json.ToBlockChain(); blockChain.IsValid().Should().BeTrue(); string resultChainHash = result.ToMerkleTree().BuildTree().ToString(); blockChainHash.Should().Be(resultChainHash); }