Exemple #1
0
        public ResultWrapper <byte[]> eth_getCode(Address address, BlockParameter?blockParameter = null)
        {
            SearchResult <BlockHeader> searchResult = _blockFinder.SearchForHeader(blockParameter);

            if (searchResult.IsError)
            {
                return(ResultWrapper <byte[]> .Fail(searchResult));
            }

            BlockHeader header = searchResult.Object;

            if (!HasStateForBlock(_blockchainBridge, header))
            {
                return(ResultWrapper <byte[]> .Fail($"No state available for block {header.Hash}",
                                                    ErrorCodes.ResourceUnavailable));
            }

            Account account = _stateReader.GetAccount(header.StateRoot, address);

            if (account == null)
            {
                return(ResultWrapper <byte[]> .Success(Array.Empty <byte>()));
            }

            var code = _stateReader.GetCode(account.CodeHash);

            return(ResultWrapper <byte[]> .Success(code));
        }
        public async Task concurrent_track_requests_will_succeed()
        {
            Random random = new Random(42);

            SingleReleaseSpecProvider spec    = new SingleReleaseSpecProvider(ConstantinopleFix.Instance, 1);
            TestRpcBlockchain         testRpc = await TestRpcBlockchain.ForTest(SealEngineType.NethDev).Build(spec);

            IStateReader   stateReader    = Substitute.For <IStateReader>();
            BaselineModule baselineModule = CreateBaselineModule(testRpc, stateReader);

            int    iterationsPerTask = 1000;
            Action trackAction       = () =>
            {
                for (int i = 0; i < iterationsPerTask; i++)
                {
                    byte[] bytes = new byte[20];
                    random.NextBytes(bytes);
                    Address address = new Address(bytes);

                    stateReader.GetCode(Arg.Any <Keccak>(), address).Returns(new byte[] { 255 });
                    var result = baselineModule.baseline_track(address).Result; // safe to invoke Result here
                    result.Result.ResultType.Should().Be(ResultType.Success);
                }
            };

            Task task1 = new Task(trackAction);
            Task task2 = new Task(trackAction);
            Task task3 = new Task(trackAction);

            task1.Start();
            task2.Start();
            task3.Start();

            await Task.WhenAll(task1, task2, task3);
        }
        private bool TryAddTree(Address trackedTree)
        {
            bool treeAdded = false;

            bool wasUntracked = _trackingOverrides.TryGetValue(trackedTree, out bool result) && result;

            if (!wasUntracked)
            {
                if (_stateReader.GetCode(_blockFinder.Head.StateRoot, trackedTree).Length != 0)
                {
                    ShaBaselineTree tree = new ShaBaselineTree(_baselineDb, _metadataBaselineDb, trackedTree.Bytes, TruncationLength, _logger);
                    treeAdded = _baselineTrees.TryAdd(trackedTree, tree);
                    if (treeAdded)
                    {
                        BaselineTreeTracker?tracker = new BaselineTreeTracker(trackedTree, tree, _blockProcessor, _baselineTreeHelper, _blockFinder, _logger);
                        _disposableStack.Push(tracker);
                    }
                }

                _trackingOverrides.TryAdd(trackedTree, false);
            }
            else
            {
                treeAdded = _trackingOverrides.TryUpdate(trackedTree, false, true);
            }

            return(treeAdded);
        }
        public async Task can_return_tracked_list(uint trackedCount)
        {
            SingleReleaseSpecProvider spec    = new SingleReleaseSpecProvider(ConstantinopleFix.Instance, 1);
            TestRpcBlockchain         testRpc = await TestRpcBlockchain.ForTest(SealEngineType.NethDev).Build(spec);

            IStateReader   stateReader    = Substitute.For <IStateReader>();
            BaselineModule baselineModule = new BaselineModule(
                testRpc.TxSender,
                stateReader,
                testRpc.LogFinder,
                testRpc.BlockTree,
                _abiEncoder,
                _fileSystem,
                new MemDb(),
                LimboLogs.Instance);

            for (int i = 0; i < trackedCount; i++)
            {
                stateReader.GetCode(null, null).ReturnsForAnyArgs(new byte[] { 255 });
                await baselineModule.baseline_track(TestItem.Addresses[i]);
            }

            var result = (await baselineModule.baseline_getTracked());

            result.Data.Length.Should().Be((int)trackedCount);
        }
Exemple #5
0
        private bool TryAddTree(Address trackedTree)
        {
            if (_stateReader.GetCode(_blockFinder.Head.StateRoot, trackedTree).Length == 0)
            {
                return(false);
            }

            ShaBaselineTree tree = new ShaBaselineTree(_baselineDb, trackedTree.Bytes, TruncationLength);

            return(_baselineTrees.TryAdd(trackedTree, tree));
        }
Exemple #6
0
        public async Task get_code_should_invoke_blockchain_bridge_get_code()
        {
            var code    = new byte[] { 0, 1, 2 };
            var address = TestItem.AddressA;

            _stateReader.GetCode(Arg.Any <Keccak>(), address).Returns(code);
            _blockFinder.Head.Returns(_anyBlock);
            var result = await _ndmBridge.GetCodeAsync(address);

            _stateReader.Received().GetCode(_anyBlock.StateRoot, address);
            result.Should().BeSameAs(code);
        }
Exemple #7
0
        public async Task track_request_will_succeed()
        {
            SingleReleaseSpecProvider spec    = new SingleReleaseSpecProvider(ConstantinopleFix.Instance, 1);
            TestRpcBlockchain         testRpc = await TestRpcBlockchain.ForTest(SealEngineType.NethDev).Build(spec);

            IStateReader   stateReader    = Substitute.For <IStateReader>();
            BaselineModule baselineModule = CreateBaselineModule(testRpc, stateReader);

            await testRpc.AddFunds(TestItem.Addresses[0], 1.Ether());

            stateReader.GetCode(Arg.Any <Keccak>(), TestItem.AddressC).Returns(new byte[] { 255 });
            var result = await baselineModule.baseline_track(TestItem.AddressC);

            result.Result.ResultType.Should().Be(ResultType.Success);
        }
        public async Task can_restore_tracking_list_on_startup(uint trackedCount)
        {
            SingleReleaseSpecProvider spec = new(ConstantinopleFix.Instance, 1);

            using TestRpcBlockchain testRpc = await TestRpcBlockchain.ForTest <BaseLineRpcBlockchain>(SealEngineType.NethDev).Build(spec);

            MemDb memDb = new();
            MemDb baselineMetaDataDb = new();

            IStateReader   stateReader    = Substitute.For <IStateReader>();
            BaselineModule baselineModule = new(
                testRpc.TxSender,
                stateReader,
                testRpc.LogFinder,
                testRpc.BlockTree,
                _abiEncoder,
                _fileSystem,
                memDb,
                baselineMetaDataDb,
                LimboLogs.Instance,
                testRpc.BlockProcessor,
                new DisposableStack());

            for (int i = 0; i < trackedCount; i++)
            {
                stateReader.GetCode(null, null).ReturnsForAnyArgs(new byte[] { 255 });
                await baselineModule.baseline_track(TestItem.Addresses[i]); // any address (no need for tree there)
            }

            BaselineModule restored = new(
                testRpc.TxSender,
                stateReader,
                testRpc.LogFinder,
                testRpc.BlockTree,
                _abiEncoder,
                _fileSystem,
                memDb,
                baselineMetaDataDb,
                LimboLogs.Instance,
                testRpc.BlockProcessor,
                new DisposableStack());

            var resultRestored = await restored.baseline_getTracked();

            resultRestored.Data.Length.Should().Be((int)trackedCount);
        }
        public void Throws_when_no_code_deployed()
        {
            IStateReader stateReader = Substitute.For <IStateReader>();
            IBlockFinder blockFinder = Substitute.For <IBlockFinder>();

            blockFinder.Head.Returns(Build.A.Block.Genesis.TestObject);

            _ndmBridge = new NdmBlockchainBridge(
                Substitute.For <IBlockchainBridge>(),
                blockFinder,
                stateReader,
                Substitute.For <ITxSender>());
            DepositService depositService  = new DepositService(_ndmBridge, _abiEncoder, _wallet, _contractAddress);
            Address        contractAddress = new Address(_ndmConfig.ContractAddress);

            stateReader.GetCode(Arg.Any <Keccak>(), contractAddress).Returns(Array.Empty <byte>());
            Assert.ThrowsAsync <InvalidDataException>(async() => await depositService.ValidateContractAddressAsync(contractAddress));
        }
        public async Task can_return_tracked_list(uint trackedCount)
        {
            SingleReleaseSpecProvider spec = new(ConstantinopleFix.Instance, 1);

            using TestRpcBlockchain testRpc = await TestRpcBlockchain.ForTest <BaseLineRpcBlockchain>(SealEngineType.NethDev).Build(spec);

            IStateReader   stateReader    = Substitute.For <IStateReader>();
            BaselineModule baselineModule = CreateBaselineModule(testRpc, stateReader);

            for (int i = 0; i < trackedCount; i++)
            {
                stateReader.GetCode(null, null).ReturnsForAnyArgs(new byte[] { 255 });
                await baselineModule.baseline_track(TestItem.Addresses[i]);
            }

            var result = (await baselineModule.baseline_getTracked());

            result.Data.Length.Should().Be((int)trackedCount);
        }
        public async Task Ok_when_code_is_valid()
        {
            IStateReader stateReader = Substitute.For <IStateReader>();
            IBlockFinder blockFinder = Substitute.For <IBlockFinder>();

            blockFinder.Head.Returns(Build.A.Block.Genesis.TestObject);

            _ndmBridge = new NdmBlockchainBridge(
                Substitute.For <IBlockchainBridge>(),
                blockFinder,
                stateReader,
                Substitute.For <ITxSender>());

            DepositService depositService  = new DepositService(_ndmBridge, _abiEncoder, _wallet, _contractAddress);
            Address        contractAddress = new Address(_ndmConfig.ContractAddress);

            stateReader.GetCode(Arg.Any <Keccak>(), contractAddress).Returns(Bytes.FromHexString(ContractData.DeployedCode));
            await depositService.ValidateContractAddressAsync(contractAddress);
        }
Exemple #12
0
 public Task <byte[]> GetCodeAsync(Address address)
 {
     byte[] code = _stateReader.GetCode(_blockTree.Head.StateRoot, address);
     return(Task.FromResult(code));
 }
Exemple #13
0
 public static byte[] GetCode(this IStateReader stateReader, Keccak stateRoot, Address address)
 {
     return(stateReader.GetCode(GetCodeHash(stateReader, stateRoot, address)) ?? Array.Empty <byte>());
 }
 public byte[] GetCode(Address address) => _stateReader.GetCode(GetAccount(address).CodeHash);
 public byte[] GetCode(Address address)
 {
     return(_stateReader.GetCode(_blockTree.Head.StateRoot, address));
 }
 public Task <byte[]> GetCodeAsync(Address address)
 {
     byte[] code = _stateReader.GetCode(_blockTree.Head?.StateRoot ?? Keccak.EmptyTreeHash, address);
     return(Task.FromResult(code));
 }
        private Task PrefetchNew(IStateReader stateReader, Block block, Keccak stateRoot, Address miner)
        {
            if (block.TotalDifficulty == null)
            {
                throw new InvalidDataException(
                          $"Received a block with null {nameof(block.TotalDifficulty)} for beam processing");
            }

            CancellationTokenSource cancellationToken;

            lock (_tokens)
            {
                cancellationToken = _tokens.GetOrAdd(block.Number, t => new CancellationTokenSource());
                if (_isDisposed)
                {
                    return(Task.CompletedTask);
                }
            }

            string description = $"[miner {miner}]";
            Task   minerTask   = Task.Run(() =>
            {
                BeamSyncContext.MinimumDifficulty.Value = block.TotalDifficulty ?? 0;
                BeamSyncContext.Description.Value       = description;
                BeamSyncContext.LastFetchUtc.Value      = DateTime.UtcNow;
                BeamSyncContext.Cancelled.Value         = cancellationToken.Token;
                stateReader.GetAccount(stateRoot, miner);
                return(BeamSyncContext.ResolvedInContext.Value);
            }).ContinueWith(t =>
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug(
                        t.IsFaulted ? $"{description} prefetch failed {t.Exception?.Message}" : $"{description} prefetch complete - resolved {t.Result}");
                }
            });

            Task senderTask = Task.Run(() =>
            {
                BeamSyncContext.MinimumDifficulty.Value = block.TotalDifficulty ?? 0;
                BeamSyncContext.Cancelled.Value         = cancellationToken.Token;
                for (int i = 0; i < block.Transactions !.Length; i++)
                {
                    Transaction tx = block.Transactions[i];
                    BeamSyncContext.Description.Value  = $"[tx prefetch {i}]";
                    BeamSyncContext.LastFetchUtc.Value = DateTime.UtcNow;

                    // TODO: is SenderAddress for sure resolved here?
                    stateReader.GetAccount(stateRoot, tx.SenderAddress !);
                }

                return(BeamSyncContext.ResolvedInContext.Value);
            }).ContinueWith(t =>
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug(
                        t.IsFaulted ? $"tx prefetch failed {t.Exception?.Message}" : $"tx prefetch complete - resolved {t.Result}");
                }
            });

            Task storageTask = Task.Run(() =>
            {
                BeamSyncContext.MinimumDifficulty.Value = block.TotalDifficulty ?? 0;
                BeamSyncContext.Cancelled.Value         = cancellationToken.Token;
                for (int i = 0; i < block.Transactions !.Length; i++)
                {
                    Transaction tx = block.Transactions[i];
                    if (tx.To != null)
                    {
                        BeamSyncContext.Description.Value  = $"[storage prefetch {i}]";
                        BeamSyncContext.LastFetchUtc.Value = DateTime.UtcNow;
                        stateReader.GetStorageRoot(stateRoot, tx.To);
                    }
                }

                return(BeamSyncContext.ResolvedInContext.Value);
            }).ContinueWith(t =>
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug(t.IsFaulted ? $"storage prefetch failed {t.Exception?.Message}" : $"storage prefetch complete - resolved {t.Result}");
                }
            });


            Task codeTask = Task.Run(() =>
            {
                BeamSyncContext.MinimumDifficulty.Value = block.TotalDifficulty.Value;
                BeamSyncContext.Cancelled.Value         = cancellationToken.Token;
                for (int i = 0; i < block.Transactions !.Length; i++)
                {
                    Transaction tx = block.Transactions[i];
                    if (tx.To != null)
                    {
                        BeamSyncContext.Description.Value  = $"[code prefetch {i}]";
                        BeamSyncContext.LastFetchUtc.Value = DateTime.UtcNow;
                        stateReader.GetCode(stateRoot, tx.To);
                    }
                }

                return(BeamSyncContext.ResolvedInContext.Value);
            }).ContinueWith(t =>
            {
                if (_logger.IsDebug)
                {
                    _logger.Debug(
                        t.IsFaulted ? $"code prefetch failed {t.Exception?.Message}" : $"code prefetch complete - resolved {t.Result}");
                }
            });

            return(Task.WhenAll(minerTask, senderTask, codeTask, storageTask));
        }
Exemple #18
0
 public byte[] GetCode(Address address) => _stateReader.GetCode(StateRoot, address);
        private void PrefetchNew(IStateReader stateReader, Block block, Keccak stateRoot, Address miner)
        {
            CancellationTokenSource cancellationToken = _tokens.GetOrAdd(block.Number, t => new CancellationTokenSource());
            string description = $"[miner {miner}]";
            Task   minerTask   = Task <int> .Run(() =>
            {
                BeamSyncContext.MinimumDifficulty.Value = block.TotalDifficulty ?? 0;
                BeamSyncContext.Description.Value       = description;
                BeamSyncContext.LastFetchUtc.Value      = DateTime.UtcNow;
                stateReader.GetAccount(stateRoot, miner);
                BeamSyncContext.Cancelled.Value = cancellationToken.Token;
                return(BeamSyncContext.ResolvedInContext.Value);
            }).ContinueWith(t => { _logger.Info(t.IsFaulted ? $"{description} prefetch failed {t.Exception.Message}" : $"{description} prefetch complete - resolved {t.Result}"); });

            Task senderTask = Task <int> .Run(() =>
            {
                BeamSyncContext.MinimumDifficulty.Value = block.TotalDifficulty ?? 0;
                for (int i = 0; i < block.Transactions.Length; i++)
                {
                    Transaction tx = block.Transactions[i];
                    BeamSyncContext.Description.Value  = $"[tx prefetch {i}]";
                    BeamSyncContext.LastFetchUtc.Value = DateTime.UtcNow;
                    BeamSyncContext.Cancelled.Value    = cancellationToken.Token;
                    // _logger.Info($"Resolved sender of {block.Number}.{i}");
                    stateReader.GetAccount(stateRoot, tx.To);
                }

                return(BeamSyncContext.ResolvedInContext.Value);
            }).ContinueWith(t => { _logger.Info(t.IsFaulted ? $"tx prefetch failed {t.Exception.Message}" : $"tx prefetch complete - resolved {t.Result}"); });

            Task storageTask = Task <int> .Run(() =>
            {
                BeamSyncContext.MinimumDifficulty.Value = block.TotalDifficulty ?? 0;
                for (int i = 0; i < block.Transactions.Length; i++)
                {
                    Transaction tx = block.Transactions[i];
                    if (tx.To != null)
                    {
                        BeamSyncContext.Description.Value = $"[storage prefetch {i}]";
                        // _logger.Info($"Resolved storage of target of {block.Number}.{i}");
                        BeamSyncContext.LastFetchUtc.Value = DateTime.UtcNow;
                        BeamSyncContext.Cancelled.Value    = cancellationToken.Token;
                        stateReader.GetStorageRoot(stateRoot, tx.To);
                    }
                }

                return(BeamSyncContext.ResolvedInContext.Value);
            }).ContinueWith(t => { _logger.Info(t.IsFaulted ? $"storage prefetch failed {t.Exception.Message}" : $"storage prefetch complete - resolved {t.Result}"); });


            Task codeTask = Task <int> .Run(() =>
            {
                BeamSyncContext.MinimumDifficulty.Value = block.TotalDifficulty.Value;
                for (int i = 0; i < block.Transactions.Length; i++)
                {
                    Transaction tx = block.Transactions[i];
                    if (tx.To != null)
                    {
                        BeamSyncContext.Description.Value = $"[code prefetch {i}]";
                        // _logger.Info($"Resolved code of target of {block.Number}.{i}");
                        BeamSyncContext.LastFetchUtc.Value = DateTime.UtcNow;
                        BeamSyncContext.Cancelled.Value    = cancellationToken.Token;
                        stateReader.GetCode(stateRoot, tx.SenderAddress);
                        return(BeamSyncContext.ResolvedInContext.Value);
                    }
                }

                return(BeamSyncContext.ResolvedInContext.Value);
            }).ContinueWith(t =>
            {
                _logger.Info(t.IsFaulted ? $"code prefetch failed {t.Exception.Message}" : $"code prefetch complete - resolved {t.Result}");
            });
        }