public async Task Can_handshake() { /* tools */ var cryptoRandom = new CryptoRandom(); var testLogger = new TestLogger(); var logManager = new OneLoggerLogManager(testLogger); /* rlpx + p2p + eth */ _keyA = TestObject.PrivateKeyA; _keyB = TestObject.PrivateKeyB; _keyC = TestObject.PrivateKeyC; var signer = new Signer(); var eciesCipher = new EciesCipher(cryptoRandom); var serializationService = Build.A.SerializationService().WithEncryptionHandshake().WithP2P().WithEth().TestObject; var encryptionHandshakeServiceA = new EncryptionHandshakeService(serializationService, eciesCipher, cryptoRandom, signer, _keyA, logManager); var encryptionHandshakeServiceB = new EncryptionHandshakeService(serializationService, eciesCipher, cryptoRandom, signer, _keyB, logManager); // var encryptionHandshakeServiceC = new EncryptionHandshakeService(serializationService, eciesCipher, cryptoRandom, signer, _keyC, logger); var syncManager = Substitute.For <ISynchronizationManager>(); Block genesisBlock = Build.A.Block.Genesis.TestObject; syncManager.Head.Returns(genesisBlock.Header); syncManager.Genesis.Returns(genesisBlock.Header); var peerServerA = new RlpxPeer(new NodeId(_keyA.PublicKey), PortA, encryptionHandshakeServiceA, serializationService, syncManager, logManager); var peerServerB = new RlpxPeer(new NodeId(_keyB.PublicKey), PortB, encryptionHandshakeServiceB, serializationService, syncManager, logManager); // var peerServerC = new RlpxPeer(_keyC.PublicKey, PortC, encryptionHandshakeServiceC, serializationService, Substitute.For<ISynchronizationManager>(), logger); await Task.WhenAll(peerServerA.Init(), peerServerB.Init()); // await Task.WhenAll(peerServerA.Init(), peerServerB.Init(), peerServerC.Init()); Console.WriteLine("Servers running..."); Console.WriteLine("Connecting A to B..."); await peerServerA.ConnectAsync(new NodeId(_keyB.PublicKey), "127.0.0.1", PortB); Console.WriteLine("A to B connected..."); // Console.WriteLine("Connecting A to C..."); // await peerServerA.ConnectAsync(_keyC.PublicKey, "127.0.0.1", PortC); // Console.WriteLine("A to C connected..."); // // Console.WriteLine("Connecting C to C..."); // await peerServerB.ConnectAsync(_keyA.PublicKey, "127.0.0.1", PortA); // Console.WriteLine("C to C connected..."); Console.WriteLine("Shutting down..."); await Task.WhenAll(peerServerA.Shutdown(), peerServerB.Shutdown()); Console.WriteLine("Goodbye..."); Assert.True(testLogger.LogList.Count(l => l.Contains("ETH received status with")) == 2, "ETH status exchange"); }
private static IKeyStore BuildKeyStore(OneLoggerLogManager logManager) { KeyStoreConfig keyStoreConfig = new KeyStoreConfig(); keyStoreConfig.KeyStoreDirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location); return(new FileKeyStore( keyStoreConfig, new EthereumJsonSerializer(), new AesEncrypter(keyStoreConfig, logManager), new CryptoRandom(), logManager)); }
public void Does_not_report_when_info_not_enabled() { _testLogger = new TestLogger(); _testLogger.IsInfo = false; OneLoggerLogManager logManager = new OneLoggerLogManager(_testLogger); JsonRpcLocalStats localStats = new JsonRpcLocalStats(_manualTimestamper, _config, logManager); localStats.ReportCall("A", 100, true); MakeTimePass(); localStats.ReportCall("A", 300, true); _testLogger.LogList.Should().HaveCount(0); }
static async Task Main(string[] args) { Rlp.RegisterDecoders(typeof(DepositDecoder).Assembly); Rlp.RegisterDecoders(typeof(DepositDetailsDecoder).Assembly); string dbPath = args[0]; ConsoleAsyncLogger asyncLogger = new ConsoleAsyncLogger(LogLevel.Info); OneLoggerLogManager logManager = new OneLoggerLogManager(asyncLogger); var deposits = await LoadDeposits(logManager, dbPath); IKeyStore keyStore = BuildKeyStore(logManager); DevKeyStoreWallet wallet = new DevKeyStoreWallet(keyStore, logManager, false); foreach (var depositGroup in deposits.Items.GroupBy(d => d.Consumer)) { Console.WriteLine($"Deposits by {depositGroup.Key}"); foreach (DepositDetails depositDetails in depositGroup) { DateTimeOffset dto = DateTimeOffset.FromUnixTimeSeconds(depositDetails.Deposit.ExpiryTime); Console.WriteLine($" [REFUNDABLE] Deposit by {depositDetails.Consumer} for {depositDetails.DataAsset.Name} {depositDetails.Deposit.Units} expired on {dto.Date:f}"); } Transaction[] refundTxs = GenerateTxsForRefunds(depositGroup, wallet); foreach (Transaction transaction in refundTxs) { Console.WriteLine(); Console.WriteLine("***************************************"); TxDecoder decoder = new TxDecoder(); Rlp txRlp = decoder.Encode(transaction); Console.WriteLine(txRlp.Bytes.ToHexString()); Console.WriteLine("***************************************"); } } Console.ReadLine(); }
public async Task Build_some_chain() { /* logging & instrumentation */ var logger = new OneLoggerLogManager(new SimpleConsoleLogger()); /* spec */ var blockMiningTime = TimeSpan.FromMilliseconds(500); var sealEngine = new FakeSealEngine(blockMiningTime); var specProvider = RopstenSpecProvider.Instance; /* store & validation */ var blockTree = new BlockTree(new MemDb(), new MemDb(), new MemDb(), specProvider, logger); var difficultyCalculator = new DifficultyCalculator(specProvider); var headerValidator = new HeaderValidator(difficultyCalculator, blockTree, sealEngine, specProvider, logger); var ommersValidator = new OmmersValidator(blockTree, headerValidator, logger); var transactionValidator = new TransactionValidator(new SignatureValidator(ChainId.Ropsten)); var blockValidator = new BlockValidator(transactionValidator, headerValidator, ommersValidator, specProvider, logger); /* state & storage */ var dbProvider = new MemDbProvider(logger); var stateTree = new StateTree(dbProvider.GetOrCreateStateDb()); var stateProvider = new StateProvider(stateTree, dbProvider.GetOrCreateCodeDb(), logger); var storageProvider = new StorageProvider(dbProvider, stateProvider, logger); /* blockchain processing */ var ethereumSigner = new EthereumSigner(specProvider, logger); var transactionStore = new TransactionStore(); var blockhashProvider = new BlockhashProvider(blockTree); var virtualMachine = new VirtualMachine(stateProvider, storageProvider, blockhashProvider, logger); var processor = new TransactionProcessor(specProvider, stateProvider, storageProvider, virtualMachine, NullTracer.Instance, logger); var rewardCalculator = new RewardCalculator(specProvider); var blockProcessor = new BlockProcessor(specProvider, blockValidator, rewardCalculator, processor, dbProvider, stateProvider, storageProvider, transactionStore, logger); var blockchainProcessor = new BlockchainProcessor(blockTree, sealEngine, transactionStore, difficultyCalculator, blockProcessor, ethereumSigner, logger); /* load ChainSpec and init */ ChainSpecLoader loader = new ChainSpecLoader(new UnforgivingJsonSerializer()); string path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\..\Chains", "ropsten.json")); logger.GetClassLogger().Info($"Loading ChainSpec from {path}"); ChainSpec chainSpec = loader.Load(File.ReadAllBytes(path)); foreach (KeyValuePair <Address, BigInteger> allocation in chainSpec.Allocations) { stateProvider.CreateAccount(allocation.Key, allocation.Value); } stateProvider.Commit(specProvider.GenesisSpec); chainSpec.Genesis.Header.StateRoot = stateProvider.StateRoot; // TODO: shall it be HeaderSpec and not BlockHeader? chainSpec.Genesis.Header.Hash = BlockHeader.CalculateHash(chainSpec.Genesis.Header); if (chainSpec.Genesis.Hash != new Keccak("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d")) { throw new Exception("Unexpected genesis hash"); } /* start processing */ sealEngine.IsMining = true; var testTransactionsGenerator = new TestTransactionsGenerator(transactionStore, ethereumSigner, blockMiningTime, logger); testTransactionsGenerator.Start(); blockchainProcessor.Start(); blockTree.SuggestBlock(chainSpec.Genesis); BigInteger roughlyNumberOfBlocks = 6; Thread.Sleep(blockMiningTime * (int)roughlyNumberOfBlocks); await blockchainProcessor.StopAsync(false); Assert.GreaterOrEqual(blockTree.Head.Number, roughlyNumberOfBlocks - 2, "number of blocks"); Assert.GreaterOrEqual(blockTree.Head.TotalTransactions, roughlyNumberOfBlocks - 2, "number of transactions"); }
public void Setup() { _manualTimestamper = new ManualTimestamper(_startTime); _testLogger = new TestLogger(); _logManager = new OneLoggerLogManager(_testLogger); }
public async Task Test() { TimeSpan miningDelay = TimeSpan.FromMilliseconds(50); /* logging & instrumentation */ var logger = new OneLoggerLogManager(new SimpleConsoleLogger(true)); /* spec */ var sealEngine = new FakeSealEngine(miningDelay); sealEngine.IsMining = true; var specProvider = RopstenSpecProvider.Instance; /* store & validation */ var blockTree = new BlockTree(new MemDb(), new MemDb(), new MemDb(), specProvider, logger); var difficultyCalculator = new DifficultyCalculator(specProvider); var headerValidator = new HeaderValidator(difficultyCalculator, blockTree, sealEngine, specProvider, logger); var ommersValidator = new OmmersValidator(blockTree, headerValidator, logger); var transactionValidator = new TransactionValidator(new SignatureValidator(ChainId.Ropsten)); var blockValidator = new BlockValidator(transactionValidator, headerValidator, ommersValidator, specProvider, logger); /* state & storage */ var codeDb = new MemDb(); var stateDb = new MemDb(); var stateTree = new StateTree(stateDb); var stateProvider = new StateProvider(stateTree, codeDb, logger); var storageDbProvider = new MemDbProvider(logger); var storageProvider = new StorageProvider(storageDbProvider, stateProvider, logger); /* blockchain processing */ var ethereumSigner = new EthereumSigner(specProvider, logger); var transactionStore = new TransactionStore(); var blockhashProvider = new BlockhashProvider(blockTree); var virtualMachine = new VirtualMachine(stateProvider, storageProvider, blockhashProvider, logger); var processor = new TransactionProcessor(specProvider, stateProvider, storageProvider, virtualMachine, NullTracer.Instance, logger); var rewardCalculator = new RewardCalculator(specProvider); var blockProcessor = new BlockProcessor(specProvider, blockValidator, rewardCalculator, processor, storageDbProvider, stateProvider, storageProvider, transactionStore, logger); var blockchainProcessor = new BlockchainProcessor(blockTree, sealEngine, transactionStore, difficultyCalculator, blockProcessor, ethereumSigner, logger, new PerfService(NullLogManager.Instance)); /* load ChainSpec and init */ ChainSpecLoader loader = new ChainSpecLoader(new UnforgivingJsonSerializer()); string path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\..\..\Chains", "ropsten.json")); logger.GetClassLogger().Info($"Loading ChainSpec from {path}"); ChainSpec chainSpec = loader.Load(File.ReadAllBytes(path)); foreach (KeyValuePair <Address, UInt256> allocation in chainSpec.Allocations) { stateProvider.CreateAccount(allocation.Key, allocation.Value); } stateProvider.Commit(specProvider.GenesisSpec); chainSpec.Genesis.Header.StateRoot = stateProvider.StateRoot; // TODO: shall it be HeaderSpec and not BlockHeader? chainSpec.Genesis.Header.Hash = BlockHeader.CalculateHash(chainSpec.Genesis.Header); if (chainSpec.Genesis.Hash != new Keccak("0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d")) { throw new Exception("Unexpected genesis hash"); } /* start processing */ blockTree.SuggestBlock(chainSpec.Genesis); blockchainProcessor.Start(); ManualResetEvent manualResetEvent = new ManualResetEvent(false); blockTree.NewHeadBlock += (sender, args) => { if (args.Block.Number == 6) { manualResetEvent.Set(); } }; manualResetEvent.WaitOne(miningDelay * 12); await blockchainProcessor.StopAsync(true).ContinueWith( t => { if (t.IsFaulted) { throw t.Exception; } Assert.GreaterOrEqual((int)blockTree.Head.Number, 6); }); }