public async Task Run()
        {
            var blockchainProxyService = new BlockchainProxyService("https://rinkeby.infura.io/v3/25e7b6dfc51040b3bfc0e47317d38f60");
            var transactionHandler     = new SimpleTransactionHandler();
            var handlers = new HandlerContainer {
                TransactionHandler = transactionHandler
            };

            //only tx sent to this address
            var transactionFilter = TransactionFilter.To("0xc0e15e11306334258d61fee52a22d15e6c9c59e0");

            var filter = new FilterContainer(transactionFilter);

            var blockProcessor = BlockProcessorFactory.Create(
                blockchainProxyService,
                handlers,
                filter,
                processTransactionsInParallel: false);

            var processingStrategy  = new ProcessingStrategy(blockProcessor);
            var blockchainProcessor = new BlockchainProcessor(processingStrategy);

            var result = await blockchainProcessor.ExecuteAsync(2830143, 2830153);

            Assert.True(result);
            Assert.Equal(12, transactionHandler.TransactionsHandled.Count);
            Assert.Empty(transactionHandler.ContractCreationTransactionsHandled);
        }
Exemplo n.º 2
0
        public RepositoryHandlerContext(IBlockchainStoreRepositoryFactory repositoryFactory)
        {
            BlockRepository              = repositoryFactory.CreateBlockRepository();
            ContractRepository           = repositoryFactory.CreateContractRepository();
            TransactionRepository        = repositoryFactory.CreateTransactionRepository();
            AddressTransactionRepository = repositoryFactory.CreateAddressTransactionRepository();
            TransactionLogRepository     = repositoryFactory.CreateTransactionLogRepository();
            TransactionVmStackRepository = repositoryFactory.CreateTransactionVmStackRepository();

            _repositories.Add(BlockRepository);
            _repositories.Add(ContractRepository);
            _repositories.Add(TransactionLogRepository);
            _repositories.Add(AddressTransactionRepository);
            _repositories.Add(TransactionLogRepository);
            _repositories.Add(TransactionVmStackRepository);

            Handlers = new HandlerContainer
            {
                BlockHandler              = new BlockRepositoryHandler(BlockRepository),
                ContractHandler           = new ContractRepositoryHandler(ContractRepository),
                TransactionHandler        = new TransactionRepositoryHandler(TransactionRepository),
                TransactionLogHandler     = new TransactionLogRepositoryHandler(TransactionLogRepository),
                TransactionVmStackHandler = new TransactionVMStackRepositoryHandler(TransactionVmStackRepository)
            };
        }
Exemplo n.º 3
0
        // ######################## FUNCTIONALITY ######################## //
        /// <summary>
        /// Register a Handler
        /// </summary>
        /// <typeparam name="T">A Network Message Type. Needs to be derived from MessageBase</typeparam>
        /// <param name="server">Register on server or on client?</param>
        /// <param name="msgType">Message type number</param>
        /// <param name="handler">Function handler which will be invoked when this type of message is recieved</param>
        /// <param name="client">If registering on a client, this is the client to register to</param>
        private static void RegisterHandler <T>(bool server, short msgType, ReceivedNetworkMessageDelegate <T> handler, NetworkClient client = null) where T : MessageBase, new()
        {
            // go through all handler containers and see if we allready have one for this msgType
            foreach (HandlerContainerBase container in _handlerContainers)
            {
                if (container.MessageId == msgType) // If we found one, register the handler function
                {
                    if (!server && container.Client != client)
                    {
                        continue;
                    }

                    HandlerContainer <T> c = (HandlerContainer <T>)container;
                    c.OnMessageReceived += handler;
                    return;
                }
            }

            // if we reach this it means there is no container for this type of message yet, so we need to add one
            HandlerContainer <T> newContainer = new HandlerContainer <T>(msgType, server, client);

            newContainer.OnMessageReceived += handler;

            _handlerContainers.Add(newContainer);
        }
Exemplo n.º 4
0
 static RestHandler()
 {
     Type t = typeof(IHandlerServices);
     Type ctxType = typeof(HttpContext);
     _handler = t.Assembly.GetTypes().Where(type => !type.IsInterface && !type.IsAbstract && t.IsAssignableFrom(type)).ToDictionary(type => Regex.Replace(type.Name, "(\\w+)Handler", "$1").ToLower(), type =>
     {
         var container = new HandlerContainer
         {
             Handler = Activator.CreateInstance(type),
             Methods = new Dictionary<string, HandlerMethodInfo>()
         };
         foreach (var method in type.GetMethods(System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public))
         {
             var name = method.Name.ToLower();
             if (!container.Methods.ContainsKey(name))
             {
                 var args = method.GetParameters();
                 var mi = new HandlerMethodInfo
                 {
                     ResultType = ServicesResult.GetResultType(method.ReturnType),
                     ArgCount = args.Length,
                     IsHttpContextArg = args.Length == 1 && args[0].ParameterType.Equals(ctxType),
                     Method = method
                 };
                 container.Methods.Add(name, mi);
             }
         }
         return container;
     });
 }
Exemplo n.º 5
0
        public async Task Run()
        {
            var web3 = new Web3.Web3(TestConfiguration.BlockchainUrls.Infura.Rinkeby);
            var transactionHandler = new SimpleTransactionHandler();
            var handlers           = new HandlerContainer {
                TransactionHandler = transactionHandler
            };

            //only tx sent to this address
            var transactionFilter = TransactionFilter.To("0xc0e15e11306334258d61fee52a22d15e6c9c59e0");

            var filter = new FilterContainer(transactionFilter);

            var blockProcessor = BlockProcessorFactory.Create(
                web3,
                handlers,
                filter,
                processTransactionsInParallel: false);

            var processingStrategy  = new ProcessingStrategy(blockProcessor);
            var blockchainProcessor = new BlockchainProcessor(processingStrategy);

            var result = await blockchainProcessor.ExecuteAsync(2830143, 2830153);

            Assert.True(result);
            Assert.Equal(12, transactionHandler.TransactionsHandled.Count);
            Assert.Empty(transactionHandler.ContractCreationTransactionsHandled);
        }
        public async Task IndexingTransferFunctions()
        {
            using (var azureSearchService = new AzureSearchService(AzureSearchServiceName, _azureSearchApiKey))
            {
                await azureSearchService.DeleteIndexAsync(AzureTransferIndexName);

                using (var azureFunctionMessageIndexer =
                           await azureSearchService.GetOrCreateFunctionIndex <TransferFunction>(indexName: AzureTransferIndexName))
                {
                    var transferHandler =
                        new FunctionIndexTransactionHandler <TransferFunction>(azureFunctionMessageIndexer);

                    var web3            = new Web3.Web3("https://rinkeby.infura.io/v3/25e7b6dfc51040b3bfc0e47317d38f60");
                    var blockchainProxy = new BlockchainProxyService(web3);
                    var handlers        = new HandlerContainer {
                        TransactionHandler = transferHandler
                    };
                    var blockProcessor      = BlockProcessorFactory.Create(blockchainProxy, handlers);
                    var processingStrategy  = new ProcessingStrategy(blockProcessor);
                    var blockchainProcessor = new BlockchainProcessor(processingStrategy);

                    var blockRange = new BlockRange(3146684, 3146694);
                    await blockchainProcessor.ProcessAsync(blockRange);

                    await Task.Delay(TimeSpan.FromSeconds(5));

                    //ensure we have written the expected docs to the index
                    Assert.Equal(3, await azureFunctionMessageIndexer.DocumentCountAsync());
                }

                await azureSearchService.DeleteIndexAsync(AzureTransferIndexName);
            }
        }
        static void Main(string[] args)
        {
            // This particular sample should be run with the following CLI args
            // A random contract on the Rinkeby network was chosen as an example
            // --Blockchain rinkeby --FromBlock   3146650

            System.Console.WriteLine("CLI args: " + string.Join(" ", args));
            var appConfig        = ConfigurationUtils.Build(args).AddConsoleLogging();
            var targetBlockchain = BlockchainSourceConfigurationFactory.Get(appConfig);

            System.Console.WriteLine($"Target Node/Name (URL): {targetBlockchain.Name}, {targetBlockchain.BlockchainUrl}");

            //only process transactions that created or called our contract
            var filters = new ContractSpecificFilterBuilder(ContractAddress).Filters;

            //for specific functions on our contract, output the name and input arg values
            var transactionRouter = new TransactionRouter();

            transactionRouter.AddContractCreationHandler(
                new ContractCreationPrinter <GlitchGoonsItemConstructor>());
            transactionRouter.AddTransactionHandler(new FunctionPrinter <BuyApprenticeFunction>());
            transactionRouter.AddTransactionHandler(new FunctionPrinter <OpenChestFunction>());

            //for specific events, output the values
            var transactionLogRouter = new TransactionLogRouter();

            transactionLogRouter.AddHandler(new EventPrinter <TransferEvent>());

            var handlers = new HandlerContainer()
            {
                TransactionHandler    = transactionRouter,
                TransactionLogHandler = transactionLogRouter,
            };

            var blockchainProxy = new BlockchainProxyService(targetBlockchain.BlockchainUrl);

            var blockProcessor = BlockProcessorFactory.Create(
                blockchainProxy,
                handlers,
                filters,
                processTransactionsInParallel: false);

            var strategy = new ProcessingStrategy(blockProcessor)
            {
                MinimumBlockConfirmations = 6 //wait for 6 block confirmations before processing block
            };

            var blockchainProcessor = new BlockchainProcessor(strategy);

            blockchainProcessor.ExecuteAsync
                (targetBlockchain.FromBlock, targetBlockchain.ToBlock)
            .GetAwaiter().GetResult();

            System.Console.WriteLine($"Contracts Created: {transactionRouter.ContractsCreated}");
            System.Console.WriteLine($"Transactions Handled: {transactionRouter.TransactionsHandled}");

            System.Console.ReadLine();
        }
Exemplo n.º 8
0
        private void LoadModules()
        {
            logger.LogDebug("Loading modules for development server.");

            HandlerContainer = new HandlerContainer(logger, testRemoteConnection);

            dynamic binPath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + Path.DirectorySeparatorChar;

            handlerLoader = new HandlerLoader(logger, testRemoteConnection, binPath, HandlerContainer);
            handlerLoader.RegisterAllHandlersToContainer();

            logger.LogDebug("Modules loaded.");
        }
Exemplo n.º 9
0
        public void RegisterHandler(int msgID, DelegateRecvHandler handler, int timeout = 0)
        {
            HandlerContainer container = new HandlerContainer();

            if (0 < timeout)
            {
                container.timer           = new System.Timers.Timer();
                container.timer.Interval  = timeout * 1000;
                container.timer.AutoReset = false;
                container.timer.Elapsed  += delegate { HandlerContainer.Timeout(this); };
                container.timer.Start();
            }
            container.handler    = handler;
            _dictHandler [msgID] = container;
        }
Exemplo n.º 10
0
        public static IBlockProcessor Create(
            IBlockchainProxyService web3, IVmStackErrorChecker vmStackErrorChecker,
            HandlerContainer handlers, FilterContainer filters = null, bool postVm = false, bool processTransactionsInParallel = true)
        {
            var transactionLogProcessor = new TransactionLogProcessor(
                filters?.TransactionLogFilters,
                handlers.TransactionLogHandler);

            var contractTransactionProcessor = new ContractTransactionProcessor(
                web3, vmStackErrorChecker, handlers.ContractHandler,
                handlers.TransactionHandler, handlers.TransactionVmStackHandler);

            var contractCreationTransactionProcessor = new ContractCreationTransactionProcessor(
                web3, handlers.ContractHandler,
                handlers.TransactionHandler);

            var valueTransactionProcessor = new ValueTransactionProcessor(
                handlers.TransactionHandler);

            var transactionProcessor = new TransactionProcessor(
                web3,
                contractTransactionProcessor,
                valueTransactionProcessor,
                contractCreationTransactionProcessor,
                transactionLogProcessor,
                filters?.TransactionFilters,
                filters?.TransactionReceiptFilters,
                filters?.TransactionAndReceiptFilters);

            if (postVm)
            {
                return new BlockVmPostProcessor(
                    web3, handlers.BlockHandler, transactionProcessor)
                       {
                           ProcessTransactionsInParallel = processTransactionsInParallel
                       }
            }
            ;

            transactionProcessor.ContractTransactionProcessor.EnabledVmProcessing = false;
            return(new BlockProcessor(
                       web3, handlers.BlockHandler, transactionProcessor, filters?.BlockFilters)
            {
                ProcessTransactionsInParallel = processTransactionsInParallel
            });
        }
    }
Exemplo n.º 11
0
        public override void OnReceive(Gamnet.Buffer buf)
        {
            recvBuffer += buf;
            while (recvBuffer.Size() >= PACKET_HEADER_SIZE)
            {
                ushort packetLength = BitConverter.ToUInt16(recvBuffer.buffer, recvBuffer.readIndex + PACKET_SIZE_OFFSET);
                if (packetLength > Gamnet.Buffer.BUFFER_SIZE)
                {
                    throw new Exception(string.Format("The packet length is greater than the buffer max length."));
                }

                if (packetLength > recvBuffer.Size())
                {
                    return;
                }

                Gamnet.Buffer tmpBuffer = new Gamnet.Buffer(recvBuffer);
                int           msgID     = BitConverter.ToInt32(tmpBuffer.buffer, tmpBuffer.readIndex + MSGID_OFFSET);
                if (false == _dictHandler.ContainsKey(msgID))
                {
                    UnityEngine.Debug.Log("msg_id:" + msgID + " is not registered");
                    ErrorEvent evt = new ErrorEvent();
                    evt.session = this;
                    evt.error   = new System.Collections.Generic.KeyNotFoundException();
                    eventQueue.Enqueue(evt);
                    return;
                }

                HandlerContainer container = _dictHandler[msgID];
                if (null != container.timer)
                {
                    container.timer.Stop();
                    container.timer.Close();
                }
                tmpBuffer.readIndex += PACKET_HEADER_SIZE;
                try
                {
                    container.handler(tmpBuffer);
                }
                catch (System.Exception) {}

                recvBuffer.readIndex += packetLength;
                recvBuffer            = new Gamnet.Buffer(recvBuffer);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Unregister a Handler
        /// </summary>
        /// <typeparam name="T">A Network Message Type. Needs to be derived from MessageBase</typeparam>
        /// <param name="msgType">Message type number</param>
        /// <param name="handler">Delegate to unregister</param>
        public static void UnregisterHandler <T>(short msgType, ReceivedNetworkMessageDelegate <T> handler) where T : MessageBase, new()
        {
            // go through all handler containers and look for the handler
            foreach (HandlerContainerBase container in _handlerContainers)
            {
                if (container.MessageId == msgType) // if we found the right handler container, unregister the delegate
                {
                    HandlerContainer <T> c = (HandlerContainer <T>)container;
                    if (!c.UnregisterDelegate(handler))
                    {
                        continue;
                    }
                    return;
                }
            }

            Debug.LogWarningFormat("Could not find {0} in registered handlers", handler.Method.Name);
        }
Exemplo n.º 13
0
        public async Task IndexingTransferFunctions()
        {
            using (var azureSearchService = new AzureSearchService(AzureSearchServiceName, _azureSearchApiKey))
            {
                await azureSearchService.DeleteIndexAsync(AzureTransferIndexName);

                try
                {
                    using (var azureFunctionMessageIndexer =
                               await azureSearchService.CreateFunctionIndexer <TransferFunction>(
                                   indexName: AzureTransferIndexName))
                    {
                        var transferHandler =
                            new FunctionIndexTransactionHandler <TransferFunction>(azureFunctionMessageIndexer);

                        var web3            = new Web3.Web3(TestConfiguration.BlockchainUrls.Infura.Rinkeby);
                        var blockchainProxy = new BlockchainProxyService(web3);
                        var handlers        = new HandlerContainer {
                            TransactionHandler = transferHandler
                        };
                        var blockProcessor      = BlockProcessorFactory.Create(blockchainProxy, handlers);
                        var processingStrategy  = new ProcessingStrategy(blockProcessor);
                        var blockchainProcessor = new BlockchainProcessor(processingStrategy);

                        var blockRange = new BlockRange(3146684, 3146694);
                        await blockchainProcessor.ProcessAsync(blockRange);

                        await Task.Delay(TimeSpan.FromSeconds(5));

                        //ensure we have written the expected docs to the index
                        Assert.Equal(3, await azureFunctionMessageIndexer.DocumentCountAsync());
                    }
                }
                finally
                {
                    await azureSearchService.DeleteIndexAsync(AzureTransferIndexName);
                }
            }
        }
Exemplo n.º 14
0
        public async Task Run()
        {
            var web3 = new Web3.Web3(TestConfiguration.BlockchainUrls.Infura.Rinkeby);
            var transactionHandler = new SimpleTransactionHandler();
            var handlers           = new HandlerContainer {
                TransactionHandler = transactionHandler
            };

            var blockProcessor = BlockProcessorFactory.Create(
                web3,
                handlers,
                processTransactionsInParallel: false);

            var processingStrategy  = new ProcessingStrategy(blockProcessor);
            var blockchainProcessor = new BlockchainProcessor(processingStrategy);

            var result = await blockchainProcessor.ExecuteAsync(2830144, 2830145);

            Assert.True(result);
            Assert.Equal(20, transactionHandler.TransactionsHandled?.Count);
            Assert.Equal(5, transactionHandler.ContractCreationsHandled?.Count);
        }
Exemplo n.º 15
0
        public async Task Run()
        {
            var contractAddresses = new[]
            { "0xd2e474c616cc60fb95d8b5f86c1043fa4552611b" };

            const ulong FromBlock = 4347;
            const ulong ToBlock   = 4347;

            var web3geth = new Web3Geth();
            var blockchainProxyService = new BlockchainProxyService(web3geth);
            var transactionHandler     = new SimpleTransactionHandler();
            var vmStackHandler         = new VmStackHandler();
            var contractHandler        = new ContractHandler();

            foreach (var contractAddress in contractAddresses)
            {
                contractHandler.ContractAddresses.Add(contractAddress);
            }

            var handlers = new HandlerContainer {
                ContractHandler = contractHandler, TransactionHandler = transactionHandler, TransactionVmStackHandler = vmStackHandler
            };

            var blockProcessor = BlockProcessorFactory.Create(
                blockchainProxyService,
                handlers,
                processTransactionsInParallel: false,
                postVm: true);

            var processingStrategy = new ProcessingStrategy(blockProcessor)
            {
            };

            var blockchainProcessor = new BlockchainProcessor(processingStrategy);

            var result = await blockchainProcessor.ExecuteAsync(FromBlock, ToBlock);

            Assert.True(result);
        }
        public async Task Run()
        {
            var blockchainProxy    = new BlockchainProxyService("https://rinkeby.infura.io/v3/25e7b6dfc51040b3bfc0e47317d38f60");
            var transactionHandler = new SimpleTransactionHandler();
            var handlers           = new HandlerContainer {
                TransactionHandler = transactionHandler
            };

            var blockProcessor = BlockProcessorFactory.Create(
                blockchainProxy,
                handlers,
                processTransactionsInParallel: false);

            var processingStrategy  = new ProcessingStrategy(blockProcessor);
            var blockchainProcessor = new BlockchainProcessor(processingStrategy);

            var result = await blockchainProcessor.ExecuteAsync(2830144, 2830145);

            Assert.True(result);
            Assert.Equal(20, transactionHandler.TransactionsHandled?.Count);
            Assert.Equal(5, transactionHandler.ContractCreationsHandled?.Count);
        }
        public void ShouldUnsubscribeFromStaleEvents()
        {
            eventBus.IsAsynchronous = false;

            var mock = new HandlerContainer();
            eventBus.Subscribe<Event1>(mock.OnFire);

            eventBus.SubscribedCount<Event1>().ShouldBe(1);

            // ---

            mock.Dispose();
            GC.Collect();

            eventBus.Publish(new Event1());
            eventBus.SubscribedCount<Event1>().ShouldBe(1);

            mock = null;
            GC.Collect(); // Only become stale after variable ref is released.

            eventBus.Publish(new Event1());
            eventBus.SubscribedCount<Event1>().ShouldBe(0);
        }
Exemplo n.º 18
0
 public static IBlockProcessor Create(IBlockchainProxyService web3,
                                      HandlerContainer handlers, FilterContainer filters = null, bool postVm = false, bool processTransactionsInParallel = true)
 {
     return(Create(web3, new VmStackErrorCheckerWrapper(), handlers, filters, postVm, processTransactionsInParallel));
 }
Exemplo n.º 19
0
 public AuthBusinessAccess(IAuthDataAccess authDataAccess, HandlerContainer handlerContainer)
 {
     this.authDataAccess   = authDataAccess;
     this.handlerContainer = handlerContainer;
 }