Пример #1
0
        private static ParityTraceAction DecodeAction(Rlp.DecoderContext context)
        {
            ParityTraceAction action = new ParityTraceAction();
            int sequenceLength       = context.ReadSequenceLength();

            if (context.ReadNumberOfItemsRemaining(context.Position + sequenceLength) == 3)
            {
                action.CallType     = "reward";
                action.RewardType   = context.DecodeString();
                action.Author       = context.DecodeAddress();
                action.Value        = context.DecodeUInt256();
                action.TraceAddress = Array.Empty <int>();
            }
            else
            {
                action.CallType       = context.DecodeString();
                action.From           = context.DecodeAddress();
                action.To             = context.DecodeAddress();
                action.Value          = context.DecodeUInt256();
                action.Gas            = context.DecodeLong();
                action.Input          = context.DecodeByteArray();
                action.Result         = new ParityTraceResult();
                action.Result.Output  = context.DecodeByteArray();
                action.Result.GasUsed = context.DecodeLong();
                action.TraceAddress   = context.DecodeArray(c => c.DecodeInt());
                int subtracesCount = context.DecodeInt();
                action.Subtraces = new List <ParityTraceAction>(subtracesCount);
                for (int i = 0; i < subtracesCount; i++)
                {
                    action.Subtraces.Add(DecodeAction(context));
                }
            }

            return(action);
        }
Пример #2
0
        private Dictionary <UInt256, ParityStateChange <byte[]> > DecodeStorageChange(Rlp.DecoderContext context)
        {
            int checkpoint = context.ReadSequenceLength();
            var change     = new Dictionary <UInt256, ParityStateChange <byte[]> >();
            int itemsCount = context.ReadNumberOfItemsRemaining(context.Position + checkpoint);

            if (itemsCount == 0)
            {
                return(null);
            }

            for (int i = 0; i < itemsCount; i = i + 2)
            {
                change[context.DecodeUInt256()] = DecodeByteChange(context);
            }

            return(change);
        }
Пример #3
0
        private Dictionary <Address, ParityAccountStateChange> DecodeStateDiff(Rlp.DecoderContext context)
        {
            var accountStateChange = new Dictionary <Address, ParityAccountStateChange>();
            int checkpoint         = context.ReadSequenceLength();
            int items = context.ReadNumberOfItemsRemaining(context.Position + checkpoint);

            if (items == 0)
            {
                return(null);
            }

            for (int i = 0; i < items; i = i + 2)
            {
                accountStateChange[context.DecodeAddress()] = DecodeAccountStateChange(context);
            }

            return(accountStateChange);
        }
Пример #4
0
        private void InitializeChain(string chainFile)
        {
            if (!File.Exists(chainFile))
            {
                if (_logger.IsInfo)
                {
                    _logger.Info($"HIVE Chain file does not exist: {chainFile}, skipping");
                }
                return;
            }

            var chainFileContent = File.ReadAllBytes(chainFile);
            var context          = new Rlp.DecoderContext(chainFileContent);
            var blocks           = new List <Block>();

            if (_logger.IsInfo)
            {
                _logger.Info($"HIVE Loading blocks from {chainFile}");
            }
            while (context.ReadNumberOfItemsRemaining() > 0)
            {
                context.PeekNextItem();
                Block block = Rlp.Decode <Block>(context);
                if (_logger.IsInfo)
                {
                    _logger.Info($"HIVE Reading a chain.rlp block {block.ToString(Block.Format.Short)}");
                }
                blocks.Add(block);
            }

            for (int i = 0; i < blocks.Count; i++)
            {
                Block block = blocks[i];
                if (_logger.IsInfo)
                {
                    _logger.Info($"HIVE Processing a chain.rlp block {block.ToString(Block.Format.Short)}");
                }
                ProcessBlock(block);
            }
        }
Пример #5
0
        private void InitializeChain(string chainFile)
        {
            if (!File.Exists(chainFile))
            {
                _logger.Info($"Chain file does not exist: {chainFile}, skipping");
                return;
            }

            var chainFileContent = File.ReadAllBytes(chainFile);
            var context          = new Rlp.DecoderContext(chainFileContent);
            var blocks           = new List <Block>();

            while (context.ReadNumberOfItemsRemaining() > 0)
            {
                context.PeekNextItem();
                blocks.Add(Rlp.Decode <Block>(context));
            }

            for (int i = 0; i < blocks.Count; i++)
            {
                ProcessBlock(blocks[i]);
            }
        }
Пример #6
0
        protected override void Decode(IChannelHandlerContext context, byte[] input, List <object> output)
        {
            if (_logger.IsTraceEnabled)
            {
                _logger.Trace("Merging frames");
            }

            Rlp.DecoderContext headerBodyItems = input.Slice(3, 13).AsRlpContext();
            int headerDataEnd   = headerBodyItems.ReadSequenceLength() + headerBodyItems.Position;
            int numberOfItems   = headerBodyItems.ReadNumberOfItemsRemaining(headerDataEnd);
            int protocolType    = headerBodyItems.DecodeInt(); // not needed - adaptive IDs
            int?contextId       = numberOfItems > 1 ? headerBodyItems.DecodeInt() : (int?)null;
            int?totalPacketSize = numberOfItems > 2 ? headerBodyItems.DecodeInt() : (int?)null;

            bool isChunked = totalPacketSize.HasValue ||
                             contextId.HasValue && _currentSizes.ContainsKey(contextId.Value);

            if (isChunked)
            {
                if (_logger.IsTraceEnabled)
                {
                    _logger.Trace("Merging chunked packet");
                }

                bool isFirstChunk = totalPacketSize.HasValue;
                if (isFirstChunk)
                {
                    _currentSizes[contextId.Value]      = 0;
                    _totalPayloadSizes[contextId.Value] = totalPacketSize.Value - 1;                                                              // packet type data size
                    _packets[contextId.Value]           = new Packet("???", GetPacketType(input), new byte[_totalPayloadSizes[contextId.Value]]); // adaptive IDs
                    _payloads[contextId.Value]          = new List <byte[]>();
                }

                int packetTypeDataSize = isFirstChunk ? 1 : 0;
                int frameSize          = input.Length - HeaderSize - FrameMacSize - packetTypeDataSize;
                _payloads[contextId.Value].Add(input.Slice(32 + packetTypeDataSize, frameSize));
                _currentSizes[contextId.Value] += frameSize;
                if (_currentSizes[contextId.Value] >= _totalPayloadSizes[contextId.Value])
                {
                    int    padding    = _currentSizes[contextId.Value] - _totalPayloadSizes[contextId.Value];
                    Packet packet     = _packets[contextId.Value];
                    int    offset     = 0;
                    int    frameCount = _payloads[contextId.Value].Count;
                    for (int i = 0; i < frameCount; i++)
                    {
                        int length = _payloads[contextId.Value][i].Length - (i == frameCount - 1 ? padding : 0);
                        Buffer.BlockCopy(_payloads[contextId.Value][i], 0, packet.Data, offset, length);
                        offset += length;
                    }

                    output.Add(packet);
                    _currentSizes.Remove(contextId.Value);
                    _totalPayloadSizes.Remove(contextId.Value);
                    _payloads.Remove(contextId.Value);
                    _packets.Remove(contextId.Value);
                }
            }
            else
            {
                int totalBodySize = input[0] & 0xFF;
                totalBodySize = (totalBodySize << 8) + (input[1] & 0xFF);
                totalBodySize = (totalBodySize << 8) + (input[2] & 0xFF);

                if (_logger.IsTraceEnabled)
                {
                    _logger.Trace($"Merging single frame packet of length {totalBodySize - 1}");
                }

                output.Add(new Packet("???", GetPacketType(input), input.Slice(1 + 32, totalBodySize - 1))); // ??? protocol because of adaptive IDs
            }
        }
Пример #7
0
        new protected async Task StartRunners(IConfigProvider configProvider)
        {
            InitRlp();
            _configProvider = configProvider;
            _initConfig     = _configProvider.GetConfig <IInitConfig>();
            _logManager     = new NLogManager(_initConfig.LogFileName, _initConfig.LogDirectory);
            _logger         = _logManager.GetClassLogger();
            _networkHelper  = new NetworkHelper(_logger);
            SetupKeyStore();
            LoadChainSpec();
            IDbConfig dbConfig = _configProvider.GetConfig <IDbConfig>();

            _dbProvider = new RocksDbProvider(_initConfig.BaseDbPath, dbConfig, _logManager, _initConfig.StoreTraces, _initConfig.StoreReceipts);

            var stateProvider = new StateProvider(
                _dbProvider.StateDb,
                _dbProvider.CodeDb,
                _logManager);

            _stateProvider = stateProvider;



            /* blockchain processing */


            if (_chainSpec.ChainId == RopstenSpecProvider.Instance.ChainId)
            {
                _specProvider = RopstenSpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == MainNetSpecProvider.Instance.ChainId)
            {
                _specProvider = MainNetSpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == RinkebySpecProvider.Instance.ChainId)
            {
                _specProvider = RinkebySpecProvider.Instance;
            }
            else if (_chainSpec.ChainId == GoerliSpecProvider.Instance.ChainId)
            {
                _specProvider = GoerliSpecProvider.Instance;
            }
            else
            {
                _specProvider = new SingleReleaseSpecProvider(Latest.Release, _chainSpec.ChainId);
            }

            _ethereumEcdsa = new EthereumEcdsa(_specProvider, _logManager);
            _txPool        = new TxPool(
                new PersistentTransactionStorage(_dbProvider.PendingTxsDb, _specProvider),
                new PendingTransactionThresholdValidator(_initConfig.ObsoletePendingTransactionInterval,
                                                         _initConfig.RemovePendingTransactionInterval), new Timestamp(),
                _ethereumEcdsa, _specProvider, _logManager, _initConfig.RemovePendingTransactionInterval,
                _initConfig.PeerNotificationThreshold);
            _receiptStorage = new PersistentReceiptStorage(_dbProvider.ReceiptsDb, _specProvider);

            _blockTree = new BlockTree(
                _dbProvider.BlocksDb,
                _dbProvider.HeadersDb,
                _dbProvider.BlockInfosDb,
                _specProvider,
                _txPool,
                _logManager);
            _recoveryStep = new TxSignaturesRecoveryStep(_ethereumEcdsa, _txPool, _logManager);
            CliqueConfig cliqueConfig = null;

            _snapshotManager = null;
            switch (_chainSpec.SealEngineType)
            {
            case SealEngineType.None:
                _sealer           = NullSealEngine.Instance;
                _sealValidator    = NullSealEngine.Instance;
                _rewardCalculator = NoBlockRewards.Instance;
                break;

            case SealEngineType.Clique:
                _rewardCalculator        = NoBlockRewards.Instance;
                cliqueConfig             = new CliqueConfig();
                cliqueConfig.BlockPeriod = _chainSpec.Clique.Period;
                cliqueConfig.Epoch       = _chainSpec.Clique.Epoch;
                _snapshotManager         = new SnapshotManager(cliqueConfig, _dbProvider.BlocksDb, _blockTree, _ethereumEcdsa, _logManager);
                _sealValidator           = new CliqueSealValidator(cliqueConfig, _snapshotManager, _logManager);
                _recoveryStep            = new CompositeDataRecoveryStep(_recoveryStep, new AuthorRecoveryStep(_snapshotManager));
                if (_initConfig.IsMining)
                {
                    _sealer = new CliqueSealer(new BasicWallet(_nodeKey), cliqueConfig, _snapshotManager, _nodeKey.Address, _logManager);
                }
                else
                {
                    _sealer = NullSealEngine.Instance;
                }

                break;

            case SealEngineType.NethDev:
                _sealer           = NullSealEngine.Instance;
                _sealValidator    = NullSealEngine.Instance;
                _rewardCalculator = NoBlockRewards.Instance;
                break;

            case SealEngineType.Ethash:
                _rewardCalculator = new RewardCalculator(_specProvider);
                var difficultyCalculator = new DifficultyCalculator(_specProvider);
                if (_initConfig.IsMining)
                {
                    _sealer = new EthashSealer(new Ethash(_logManager), _logManager);
                }
                else
                {
                    _sealer = NullSealEngine.Instance;
                }

                _sealValidator = new EthashSealValidator(_logManager, difficultyCalculator, new Ethash(_logManager));
                break;

            default:
                throw new NotSupportedException($"Seal engine type {_chainSpec.SealEngineType} is not supported in Nethermind");
            }


            _headerValidator = new HeaderValidator(
                _blockTree,
                _sealValidator,
                _specProvider,
                _logManager);

            var ommersValidator = new OmmersValidator(
                _blockTree,
                _headerValidator,
                _logManager);
            var storageProvider = new StorageProvider(
                _dbProvider.StateDb,
                stateProvider,
                _logManager);

            var txValidator = new TxValidator(_specProvider.ChainId);

            _blockValidator = new BlockValidator(
                txValidator,
                _headerValidator,
                ommersValidator,
                _specProvider,
                _logManager);



            var blockhashProvider = new BlockhashProvider(
                _blockTree, _logManager);

            var virtualMachine = new VirtualMachine(
                stateProvider,
                storageProvider,
                blockhashProvider,
                _logManager);

            var transactionProcessor = new TransactionProcessor(
                _specProvider,
                stateProvider,
                storageProvider,
                virtualMachine,
                _logManager);

            _blockProcessor = new BlockProcessor(
                _specProvider,
                _blockValidator,
                _rewardCalculator,
                transactionProcessor,
                _dbProvider.StateDb,
                _dbProvider.CodeDb,
                _dbProvider.TraceDb,
                stateProvider,
                storageProvider,
                _txPool,
                _receiptStorage,
                _configProvider.GetConfig <ISyncConfig>(),
                _logManager);

            _blockchainProcessor = new BlockchainProcessor(
                _blockTree,
                _blockProcessor,
                _recoveryStep,
                _logManager,
                _initConfig.StoreReceipts,
                _initConfig.StoreTraces);


            string chainFile = Path.Join(Path.GetDirectoryName(_initConfig.ChainSpecPath), "chain.rlp");

            if (!File.Exists(chainFile))
            {
                _logger.Info($"Chain file does not exist: {chainFile}, skipping");
                return;
            }

            var chainFileContent = File.ReadAllBytes(chainFile);
            var context          = new Rlp.DecoderContext(chainFileContent);
            var blocks           = new List <Block>();

            while (context.ReadNumberOfItemsRemaining() > 0)
            {
                context.PeekNextItem();
                blocks.Add(Rlp.Decode <Block>(context));
            }

            for (int i = 0; i < blocks.Count; i++)
            {
                ProcessBlock(blocks[i]);
            }
        }