Esempio n. 1
0
        public GenericResponse Transfer(TransactionTransferRequest value)
        {
            try
            {
                VerifySignature(value.Body, value.Signature, value.Body.Sender);

                if (!ApplicationState.IsChainUpToDate)
                {
                    return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.NodeNotConsensusReady));
                }

                //Perform transaction
                TransactionServices transactionService = new TransactionServices();
                string txId = transactionService.AddTransfer(
                    value.Body.Nonce,
                    Convert.ToDecimal(value.Body.Fee),
                    value.Body.TokenSymbol,
                    value.Body.Sender,
                    value.Body.ToAddress,
                    Convert.ToDecimal(value.Body.Amount));

                ApplicationLog.Info("Transaction added to queue for next block. TxId: " + txId);
                return(new GenericResponse(txId, ResponseCodes.Success, "Transaction added to queue for next block."));
            }
            catch (ValidationException vex)
            {
                ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message);
                return(new GenericResponse(null, vex.Code, vex.Message));
            }
            catch (Exception ex)
            {
                ApplicationLog.Exception(ex);
                return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error));
            }
        }
Esempio n. 2
0
        public void SyncChain(NodeChainHeight longestChainNode)
        {
            ApplicationLog.Info("Downloading chain.");

            ApplicationState.ConsensusState = ConsensusStates.SyncingChain;

            ViewerServices viewerServices = new ViewerServices();
            int            localHeight    = viewerServices.GetChainHeight();

            if (localHeight < 0)
            {
                localHeight = 0;
            }

            //TODO: Future enhancement to download from different nodes in parellel
            int currentHeight = localHeight;
            int lastHeight    = longestChainNode.ChainHeight;

            while (currentHeight <= lastHeight)
            {
                var blocks = GetBlocks(longestChainNode.Address, currentHeight, currentHeight + 10);
                foreach (var block in blocks)
                {
                    AddBlockToChain(block);
                    currentHeight++;
                }
            }
        }
Esempio n. 3
0
        public GenericResponse AddOrderMarket(TransactionOrderMarketRequest value)
        {
            try
            {
                VerifySignature(value.Body, value.Signature, value.Body.Owner);

                if (!ApplicationState.IsChainUpToDate)
                {
                    return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.NodeNotConsensusReady));
                }

                //Perform transaction
                TransactionServices transactionService = new TransactionServices();
                List <string>       txIds = transactionService.AddMarketOrder(
                    value.Body.Nonce,
                    Convert.ToDecimal(value.Body.Fee),
                    value.Body.PairSymbol,
                    value.Body.Side,
                    Convert.ToDecimal(value.Body.Amount),
                    value.Body.Owner);

                ApplicationLog.Info("Transaction added to queue for next block.");
                return(new GenericResponse(txIds, ResponseCodes.Success, "Transaction added to queue for next block."));
            }
            catch (ValidationException vex)
            {
                ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message);
                return(new GenericResponse(null, vex.Code, vex.Message));
            }
            catch (Exception ex)
            {
                ApplicationLog.Exception(ex);
                return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error));
            }
        }
Esempio n. 4
0
        private int GetLongestChain(out Node longestNode)
        {
            ApplicationLog.Info("Getting longest chain.");

            int  longestChain       = -1;
            Node longestNetworkNode = null;

            //TODO: In order not to overload the node with longest chain, get a list of nodes
            //with longest chain and randomly select one to server

            var nodes = ApplicationState.ConnectedNodes;

            Parallel.ForEach(nodes, new ParallelOptions {
                MaxDegreeOfParallelism = ConstantConfig.BroadcastThreadCount
            }, networkNode =>
            {
                ApiClient api = new ApiClient(networkNode.ServerAddress);
                int height    = api.GetChainHeight();

                if (height > longestChain)
                {
                    longestChain       = height;
                    longestNetworkNode = networkNode;
                }
            });

            longestNode = longestNetworkNode;

            return(longestChain);
        }
Esempio n. 5
0
        public GenericResponse CreateNewChain(string ownerAddress)
        {
            try
            {
                DataServices dataService = new DataServices();

                if (dataService.HasLocalChainData())
                {
                    throw new Exception("Chain folder is not empty. Please delete the existing chain folder first before creating a new chain.");
                }

                ApplicationLog.Info("Creating new chain...");

                dataService.CreateGenesisBlock(
                    ownerAddress,
                    Settings.NewChainSetup.NativeTokenName,
                    Settings.NewChainSetup.NativeTokenSymbol,
                    Settings.NewChainSetup.InitialSupply,
                    Settings.NewChainSetup.Decimals);

                ApplicationLog.Info("Chain created successfully.");

                return(new GenericResponse("Chain created successfully.", ResponseCodes.Success, ResponseMessages.Success));
            }
            catch (ValidationException vex)
            {
                ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message);
                return(new GenericResponse(null, vex.Code, vex.Message));
            }
            catch (Exception ex)
            {
                ApplicationLog.Exception(ex);
                return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error));
            }
        }
Esempio n. 6
0
        public GenericResponse DeleteLocalChain()
        {
            try
            {
                DataServices dataService = new DataServices();

                if (dataService.HasLocalChainData())
                {
                    dataService.DeleteLocalChain();
                }

                ApplicationLog.Info("Local chain data deleted successfully.");

                return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success));
            }
            catch (ValidationException vex)
            {
                ApplicationLog.Warn("ValidationException [" + vex.Code + "]: " + vex.Message);
                return(new GenericResponse(null, vex.Code, vex.Message));
            }
            catch (Exception ex)
            {
                ApplicationLog.Exception(ex);
                return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error));
            }
        }
Esempio n. 7
0
        public GenericResponse GetConnectedNodes()
        {
            try
            {
                ApplicationLog.Info("Retrieving connected nodes.");

                var nodes = ApplicationState.ConnectedNodes;

                //Filter out nodes flagged as disconnected
                foreach (var disconnectedNode in ApplicationState.DisconnectedNodes)
                {
                    if (disconnectedNode.ServerAddress != ApplicationState.Node.ServerAddress)
                    {
                        var removeNode = nodes.Where(x => x.ServerAddress == disconnectedNode.ServerAddress).FirstOrDefault();
                        if (removeNode != null)
                        {
                            nodes.Remove(removeNode);
                        }
                    }
                }

                return(new GenericResponse(nodes, ResponseCodes.Success, ResponseMessages.Success));
            }
            catch (Exception ex)
            {
                ApplicationLog.Exception(ex);
                return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error));
            }
        }
Esempio n. 8
0
        public void SelectSpeaker()
        {
            ApplicationState.ConsensusState = ConsensusStates.SelectingSpeaker;

            //Draw speaker from consensus pool
            var speakerNode = DrawSpeaker();

            ApplicationLog.Info(string.Format("Speaker IP: {0}", speakerNode.ServerAddress));

            //Set to state
            ApplicationState.CurrentSpeaker = speakerNode;

            if (ApplicationState.Node.ServerAddress == ApplicationState.CurrentSpeaker.ServerAddress)
            {
                //This node is the speaker
                CreateAndAnnounceBlockHeaderAsync();
            }
            else
            {
                //Timeout configuration on WaitingForSpeaker
                ApplicationState.SpeakerTimeoutTimer          = new System.Timers.Timer();
                ApplicationState.SpeakerTimeoutTimer.Interval = 20 * 1000;
                ApplicationState.SpeakerTimeoutTimer.Elapsed += SpeakerTimeoutTimer_Elapsed;
                ApplicationState.SpeakerTimeoutTimer.Start();
            }

            ApplicationState.ConsensusState = ConsensusStates.WaitingForSpeaker;
        }
Esempio n. 9
0
        public void Execute(IJobExecutionContext context)
        {
            string msg = string.Format("-----【{0}】处理Job1的逻辑------{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"));

            Console.WriteLine(msg);
            ApplicationLog.Info(msg);
        }
Esempio n. 10
0
        public void Execute(IJobExecutionContext context)
        {
            var msg = string.Format("*****【{0}】处理Job2的逻辑*****{1}", Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("r"));

            Console.WriteLine(msg);
            ApplicationLog.Info(msg);
        }
Esempio n. 11
0
        private Node DrawSpeaker()
        {
            ApplicationLog.Info("Drawing speaker from proof of stake pool.");

            var drawResult = ApplicationState.PosPool.DrawSpeaker();

            return(ApplicationState.ConnectedNodes.Where(x => x.WalletAddress == drawResult.WalletAddress).FirstOrDefault());
        }
Esempio n. 12
0
        public async Task <CommonResponse <string> > BorrowRegisterNotify(int dayLimit)
        {
            var response = new CommonResponse <string>();

            try
            {
                var list = await _db.BorrowRegister.Where(c => !c.Deleted && c.ReturnDate <= DateTime.Now.AddDays(dayLimit) && (!c.ReturnNotified.HasValue || c.ReturnNotified.Value == false) &&
                                                          (c.Status == BorrowRegisterStatus.Borrowed || c.Status == BorrowRegisterStatus.Overdue || c.Status == BorrowRegisterStatus.Renewed))
                           .OrderBy(c => c.Id).Take(50).ToListAsync();

                var archivesList = await _db.ArchivesInfo.Join(_db.BorrowRegisterDetail, a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                                   .Where(j => list.Select(l => l.Id).Contains(j.b.BorrowRegisterId))
                                   .Select(c => new
                {
                    c.a.ProjectName,
                    c.b.Id,
                    c.b.BorrowRegisterId
                }).ToListAsync();

                if (list.Any())
                {
                    list.ForEach(c =>
                    {
                        var projectName = archivesList.FirstOrDefault(a => a.BorrowRegisterId == c.Id);

                        ApplicationLog.Info("task.SMS_171116662." + c.Phone + "." + c.Id);
                        var msgRes = OssHelper.SendSms("SMS_171116662", c.Phone, $"{{\"name\":\"{c.Borrower}\", \"PtName\":\"{(projectName != null ? projectName.ProjectName : string.Empty)}\", \"RDate\":\"{c.ReturnDate.ToString("yyyy-MM-dd")}\" }}");
                        //循环发送短信
                        if (msgRes.Code == "OK")
                        {
                            c.ReturnNotified = true;
                            c.NotifyCount    = c.NotifyCount.GetValueOrDefault() + 1;
                            c.UpdateTime     = DateTime.Now;
                        }
                    });
                    var data = list.Select(c => c.Id).Serialize();
                    await _db.OperationLog.AddAsync(new OperationLog
                    {
                        Action     = OperationAction.Create,
                        Name       = "催还短信",
                        CreateTime = DateTime.Now,
                        BeforeData = data
                    });

                    await _db.SaveChangesAsync();

                    response.Data = data;
                }
                response.Success = true;
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
                ApplicationLog.Error("BorrowRegisterNotify", ex);
            }

            return(response);
        }
Esempio n. 13
0
        public async Task <CommonResponse <string> > ReturnWarn(ReturnWarnRequest request)
        {
            var response = new CommonResponse <string>();

            try
            {
                if (request == null)
                {
                    throw new BizException("参数不能为空");
                }

                var borrowRegister = await _db.BorrowRegister.FirstAsync(c => c.Id == request.BorrowRegisterId);

                if (borrowRegister == null)
                {
                    throw new BizException("借阅记录不存在");
                }

                if (!(borrowRegister.Status == BorrowRegisterStatus.Borrowed || borrowRegister.Status == BorrowRegisterStatus.Overdue || borrowRegister.Status == BorrowRegisterStatus.Renewed))
                {
                    throw new BizException("借阅登记状态为:已借出、延期、逾期 才能催还");
                }

                //var archives = await _db.ArchivesInfo.Join(_db.BorrowRegisterDetail.Where(j => j.BorrowRegisterId == borrowRegister.Id).Take(1), a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                //    .Select(c => new
                //    {
                //        c.a.ProjectName,
                //        c.b.Id
                //    }).FirstOrDefaultAsync();
                var projects = await _db.BorrowRegisterDetail.AsNoTracking().FirstOrDefaultAsync(c => c.BorrowRegisterId == borrowRegister.Id);

                ApplicationLog.Info("SMS_171116662." + borrowRegister.Phone + "." + borrowRegister.Id);
                var msgRes = OssHelper.SendSms("SMS_171116662", borrowRegister.Phone, $"{{\"name\":\"{borrowRegister.Borrower}\", \"PtName\":\"{(projects?.ProjectName)}\", \"RDate\":\"{borrowRegister.ReturnDate.ToString("yyyy-MM-dd")}\" }}");

                if (msgRes.Code == "OK")
                {
                    borrowRegister.ReturnNotified = true;
                    borrowRegister.NotifyCount    = borrowRegister.NotifyCount.GetValueOrDefault() + 1;
                    borrowRegister.UpdateTime     = DateTime.Now;
                    await _db.SaveChangesAsync();

                    response.Data = borrowRegister.NotifyCount.ToString();
                }
                response.Success = true;
            }
            catch (BizException ex)
            {
                response.Message = ex.Message;
            }
            catch (Exception ex)
            {
                response.Message = "催还发生异常";
                ApplicationLog.Error("ReturnWarn", ex);
            }

            return(response);
        }
 public void Info(string message, Exception exception = null)
 {
     if (string.IsNullOrWhiteSpace(message))
     {
         return;
     }
     message = string.Concat(LogPrefix, message);
     ApplicationLog.Info(message + (exception == null ? "" : exception.Message));
 }
Esempio n. 15
0
        /// <summary>
        /// Dumps *ALL* registered network events to the log
        /// </summary>
        private void PrintDebug()
        {
            var sb           = new StringBuilder();
            var methodLookup = (Dictionary <MethodInfo, CallSite>) typeof(MyEventTable).GetField("m_methodInfoLookup", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(m_typeTable.StaticEventTable);

            sb.Append("###Static events:");
            foreach (var entry in methodLookup)
            {
                sb.Append(entry.Key.DeclaringType?.FullName + "." + entry.Key.Name + "(");
                var parameters = entry.Key.GetParameters();
                for (int i = 0; i < parameters.Length; i++)
                {
                    sb.Append(parameters[i].ParameterType);
                    sb.Append(" " + parameters[i].Name);
                    if (i < parameters.Length - 1)
                    {
                        sb.Append(", ");
                    }
                }
                sb.AppendLine(")");
            }

            var typelookup = (Dictionary <Type, MySynchronizedTypeInfo>) typeof(MyTypeTable).GetField("m_typeLookup", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(m_typeTable);

            foreach (var entry in typelookup)
            {
                var lookup = (Dictionary <MethodInfo, CallSite>) typeof(MyEventTable).GetField("m_methodInfoLookup", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entry.Value.EventTable);
                if (!lookup.Any())
                {
                    continue;
                }

                sb.AppendLine();
                sb.AppendLine();
                sb.Append($"###{entry.Key} events:");

                foreach (var ent in lookup)
                {
                    sb.AppendLine();
                    sb.Append(ent.Key.DeclaringType?.FullName + "." + ent.Key.Name + "(");
                    var parameters = ent.Key.GetParameters();
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        sb.Append(parameters[i].ParameterType);
                        sb.Append(" " + parameters[i].Name);
                        if (i < parameters.Length - 1)
                        {
                            sb.Append(", ");
                        }
                    }
                    sb.Append(")");
                }
            }

            ApplicationLog.Info(sb.ToString());
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            //log4net配置
            XmlConfigurator.Configure();
            ApplicationLog.Info("程序开启!");
            Console.WriteLine("********************程序开始执行******************");
            ScheduleBase.Scheduler.Start();

            ScheduleBase.AddScheduler(new JobService1());
            ScheduleBase.AddScheduler(new JobService2());

            Console.ReadKey();
        }
Esempio n. 17
0
        public async void NextEpoch()
        {
            try
            {
                ApplicationLog.Info("Beginning new epoch iteration");

                ApplicationState.ConsensusState = ConsensusStates.BeginningEpoch;

                ApplicationState.CurrentSpeaker = null;
                NodeChainHeight longestChainNode = null;

                if (ApplicationState.DisconnectedNodes.Count > 0)
                {
                    RemoveDisconnectedNodes();
                    //TODO: subsequent epoch can retrieve network nodes from other nodes instead of from seed
                    RetrieveNetworkNodes();
                }

                if (IsChainUpToDate(out longestChainNode))
                {
                    ApplicationState.IsChainUpToDate = true;
                    ApplicationState.LiveEpochCount++;
                    SelectSpeaker();
                }
                else
                {
                    ApplicationState.IsChainUpToDate = false;
                    SyncChain(longestChainNode);

                    ApplicationState.LiveEpochCount = 0;
                    ApplicationState.PendingRecords.Clear();

                    RegisterSelfOnNetwork(ApplicationState.Node.WalletAddress, ApplicationState.Node.Signature, false);

                    NextEpoch();
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.Exception(ex);
                ApplicationLog.Info("Retry in 30 seconds.");
                await Task.Delay(30 * 1000);

                NextEpoch();
            }
        }
Esempio n. 18
0
        public void InitNetworkIntercept()
        {
            m_typeTable = typeof(MyReplicationLayerBase).GetField(TypeTableField, BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(MyMultiplayer.ReplicationLayer) as MyTypeTable;
            //don't bother with nullchecks here, it was all handled in ReflectionUnitTest
            var transportType     = typeof(MySyncLayer).GetField(MyTransportLayerField, BindingFlags.NonPublic | BindingFlags.Instance).FieldType;
            var transportInstance = typeof(MySyncLayer).GetField(MyTransportLayerField, BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(MyMultiplayer.Static.SyncLayer);
            var handlers          = (Dictionary <MyMessageId, Action <MyPacket> >)transportType.GetField(TransportHandlersField, BindingFlags.NonPublic | BindingFlags.Instance)?.GetValue(transportInstance);

            //remove Keen's network listener
            handlers.Remove(MyMessageId.RPC);
            //replace it with our own
            handlers.Add(MyMessageId.RPC, ProcessEvent);

            //PrintDebug();

            ApplicationLog.Info("Initialized network intercept!");
        }
Esempio n. 19
0
        public void RegisterSelfOnNetwork(string walletAddress, string signature, bool broadcast)
        {
            ApplicationLog.Info("Registering self on the network.");

            //Broadcast to other nodes
            if (broadcast)
            {
                var nodes = ApplicationState.ConnectedNodesExceptSelf;
                Parallel.ForEach(nodes, new ParallelOptions {
                    MaxDegreeOfParallelism = ConstantConfig.BroadcastThreadCount
                }, networkNode =>
                {
                    ApiClient api = new ApiClient(networkNode.ServerAddress);
                    api.AnnounceRegisterNode(ApplicationState.ServerAddress, walletAddress, signature);
                });
            }

            //Register self in local nodes cache

            //Get wallet balance
            decimal       walletBalance = 0;
            IndexServices indexServices = new IndexServices();
            var           nativeToken   = indexServices.TokenIndex.GetNative();

            if (nativeToken != null) //Native token would be null if chain has not yet been sync / no local chain
            {
                var walletIndex = indexServices.BalanceIndex.Get(walletAddress, indexServices.TokenIndex.GetNative().Symbol);
                if (walletIndex != null)
                {
                    walletBalance = walletIndex.Balance;
                }
            }

            //Add node to local consensus ledger
            Node node = new Node()
            {
                ServerAddress = ApplicationState.ServerAddress,
                WalletAddress = walletAddress,
                Signature     = signature,
                Balance       = walletBalance
            };

            AddConsensusNode(node);
            ApplicationState.Node = node;
        }
Esempio n. 20
0
        public async void CreateAndAnnounceBlockHeaderAsync()
        {
            ApplicationState.ConsensusState = ConsensusStates.CreatingBlock;

            //Get last block timestamp
            DataServices dataService = new DataServices();
            var          lastBlock   = dataService.LastBlock;

            if (lastBlock == null)
            {
                throw new Exception("Not last block available.");
            }

            int lastBlockTimestamp = lastBlock.Header.Timestamp;

            //Calculate next block timestamp
            int nextBlockTime = lastBlockTimestamp + ConstantConfig.BlockInterval;
            int currentTime   = DateTimeUtility.ToUnixTime(DateTime.UtcNow);

            //Wait until next block time
            if (nextBlockTime > currentTime)
            {
                int secondsToWait = nextBlockTime - currentTime;
                ApplicationLog.Info("Time until next block (seconds): " + secondsToWait);

                await Task.Delay(secondsToWait * 1000);
            }

            ApplicationLog.Info("Creating new block header");

            //Create new block
            var header = dataService.CreateBlockHeader();

            //Broadcast new block to network
            var nodes = ApplicationState.ConnectedNodes;

            Parallel.ForEach(nodes, new ParallelOptions {
                MaxDegreeOfParallelism = ConstantConfig.BroadcastThreadCount
            }, networkNode =>
            {
                ApiClient api = new ApiClient(networkNode.ServerAddress);
                api.AnnounceNewBlock(header);
            });
        }
Esempio n. 21
0
        private void Echo(string endpoint, string data)
        {
            try
            {
                ApplicationLog.Info("Relaying echo.");

                var nodes = ApplicationState.ConnectedNodes;
                Parallel.ForEach(nodes, new ParallelOptions {
                    MaxDegreeOfParallelism = ConstantConfig.BroadcastThreadCount
                }, networkNode =>
                {
                    ApiClient api = new ApiClient(networkNode.ServerAddress);
                    var response  = api.SendPostRequest(endpoint, data);
                });
            }
            catch
            {
                throw;
            }
        }
Esempio n. 22
0
        public GenericResponse RegisterNodeAnnouncement(string serverAddress, string walletAddress, string signature)
        {
            try
            {
                VerifySignature(walletAddress, signature, walletAddress);

                //Get wallet balance
                decimal       walletBalance = 0;
                IndexServices indexServices = new IndexServices();
                var           nativeToken   = indexServices.TokenIndex.GetNative();
                if (nativeToken != null) //Native token would be null if chain has not yet been sync / no local chain
                {
                    var walletIndex = indexServices.BalanceIndex.Get(walletAddress, indexServices.TokenIndex.GetNative().Symbol);
                    if (walletIndex != null)
                    {
                        walletBalance = walletIndex.Balance;
                    }
                }

                //Add node to consensus
                Node node = new Node()
                {
                    ServerAddress = serverAddress,
                    WalletAddress = walletAddress,
                    Signature     = signature,
                    Balance       = walletBalance
                };

                ConsensusServices consensusService = new ConsensusServices();
                consensusService.AddConsensusNode(node);

                ApplicationLog.Info("Registered node: " + node.ServerAddress);

                return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success));
            }
            catch (Exception ex)
            {
                ApplicationLog.Exception(ex);
                return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error));
            }
        }
Esempio n. 23
0
        public void RetrieveNetworkNodes()
        {
            ApplicationLog.Info("Updating nodes addresses.");

            ApplicationState.ConsensusState = ConsensusStates.UpdatingNodes;

            //Retrieve entire list of network nodes from seed
            foreach (var seed in Settings.ProtocolConfiguration.SeedList)
            {
                ApiClient api   = new ApiClient(seed);
                var       nodes = api.GetNodes();
                if (nodes != null)
                {
                    //Update nodes to local memory
                    AddConsensusNodes(nodes);
                    break;
                }
            }

            //TODO: fallback if failed to retrieve from seed, get from connected nodes
        }
Esempio n. 24
0
        private void RemoveDisconnectedNodes()
        {
            if (ApplicationState.DisconnectedNodes.Count > 0)
            {
                ApplicationLog.Info("Removing disconnected nodes.");

                foreach (var disconnectedNode in ApplicationState.DisconnectedNodes)
                {
                    if (disconnectedNode.ServerAddress != ApplicationState.Node.ServerAddress)
                    {
                        var removeNode = ApplicationState.ConnectedNodes.Where(x => x.ServerAddress == disconnectedNode.ServerAddress).FirstOrDefault();
                        if (removeNode != null)
                        {
                            ApplicationState.ConnectedNodes.Remove(removeNode);
                        }
                    }
                }

                ApplicationState.DisconnectedNodes.Clear();
            }
        }
Esempio n. 25
0
        public async Task <CommonResponse <string> > ConfirmBorrowed(ConfirmBorrowedRequest request)
        {
            var response = new CommonResponse <string>();

            using (var trans = await _db.Database.BeginTransactionAsync())
            {
                try
                {
                    if (request == null)
                    {
                        throw new BizException("参数不能为空");
                    }

                    var borrowRegister = await _db.BorrowRegister.FirstOrDefaultAsync(c => c.Id == request.BorrowRegisterId && !c.Deleted);

                    if (borrowRegister == null)
                    {
                        throw new BizException("借阅登记不存在");
                    }

                    if (borrowRegister.Status == BorrowRegisterStatus.Borrowed)
                    {
                        //response.Message = "当前状态已经借出";
                        //response.ErrorCode = 1;
                        //response.Success = true;
                        //return response;
                        throw new BizException("当前借阅的状态为已借出");
                    }

                    if (borrowRegister.Status != BorrowRegisterStatus.Registered)
                    {
                        throw new BizException("借阅登记状态为:已登记 才能确认借出");
                    }

                    /*
                     * var archives = await _db.ArchivesInfo.Join(_db.BorrowRegisterDetail, a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                     *  .Where(j => j.b.BorrowRegisterId == borrowRegister.Id)
                     *  .Select(c => c.a).ToListAsync();
                     * //如果当前状态为init,将档案改为
                     * archives.ForEach(c =>
                     * {
                     *  switch (c.Status)
                     *  {
                     *      case ArchivesStatus.Init:
                     *      case ArchivesStatus.Normal:
                     *          c.Status = ArchivesStatus.Borrowed;
                     *          break;
                     *      case ArchivesStatus.Borrowed:
                     *          throw new BizException("您选择的档案可能已借出,无法再次借阅");
                     *      default:
                     *          throw new BizException("您选择的档案档案当前状态出错,无法确认借出");
                     *  }
                     * });
                     */
                    borrowRegister.UpdateTime = DateTime.Now;
                    borrowRegister.Status     = BorrowRegisterStatus.Borrowed;
                    borrowRegister.UpdateTime = DateTime.Now;

                    await _db.SaveChangesAsync();

                    trans.Commit();
                    response.Success = true;

                    var projects = await _db.BorrowRegisterDetail.AsNoTracking().FirstOrDefaultAsync(c => c.BorrowRegisterId == borrowRegister.Id);

                    ApplicationLog.Info("SMS_171116670." + borrowRegister.Phone + "." + borrowRegister.Id);
                    var msgRes = OssHelper.SendSms("SMS_171116670", borrowRegister.Phone, $"{{\"name\":\"{borrowRegister.Borrower}\", \"PtName\":\"{(projects?.ProjectName)}\", \"RDate\":\"{borrowRegister.ReturnDate.ToString("yyyy-MM-dd")}\" }}");
                }
                catch (BizException ex)
                {
                    trans.Rollback();
                    response.Message = ex.Message;
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    response.Message = "提交续借发生异常";
                    ApplicationLog.Error("ConfirmBorrowed", ex);
                }
            }

            return(response);
        }
Esempio n. 26
0
        /// <summary>
        /// 续借
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task <CommonResponse <string> > RenewBorrow(RenewBorrowRequest request)
        {
            var response = new CommonResponse <string>();

            try
            {
                if (request == null)
                {
                    throw new BizException("参数不能为空");
                }

                if (request.RenewDate < DateTime.Now)
                {
                    throw new BizException("续借日期不能小于当天");
                }

                var borrowRegister = await _db.BorrowRegister.FirstOrDefaultAsync(c => c.Id == request.BorrowRegisterId && !c.Deleted);

                if (borrowRegister == null)
                {
                    throw new BizException("借阅登记不存在");
                }

                if (!(borrowRegister.Status == BorrowRegisterStatus.Renewed || borrowRegister.Status == BorrowRegisterStatus.Overdue || borrowRegister.Status == BorrowRegisterStatus.Borrowed))
                {
                    throw new BizException("借阅登记状态为:已借出、延期、逾期 才能续借");
                }

                borrowRegister.ReturnDate     = request.RenewDate;
                borrowRegister.Status         = BorrowRegisterStatus.Renewed;
                borrowRegister.UpdateTime     = DateTime.Now;
                borrowRegister.ReturnNotified = false;
                await _db.SaveChangesAsync();

                response.Success = true;

                var projects = await _db.BorrowRegisterDetail.AsNoTracking().FirstOrDefaultAsync(c => c.BorrowRegisterId == borrowRegister.Id);

                try
                {
                    //var archivesFirst = await _db.ArchivesInfo.AsNoTracking().Join(_db.BorrowRegisterDetail.AsNoTracking().Where(j => j.BorrowRegisterId == borrowRegister.Id).Take(1),
                    //    a => a.Id, b => b.ArchivesId, (a, b) => new { a, b })
                    //    .Select(c => new
                    //    {
                    //        c.a.ProjectName
                    //    }).FirstOrDefaultAsync();
                    ApplicationLog.Info("SMS_171116665." + borrowRegister.Phone + "." + borrowRegister.Id);
                    var msgRes = OssHelper.SendSms("SMS_171116665", borrowRegister.Phone, $"{{\"name\":\"{borrowRegister.Borrower}\", \"PtName\":\"{(projects?.ProjectName)}\", \"RDate\":\"{borrowRegister.ReturnDate.ToString("yyyy-MM-dd")}\" }}");
                }
                catch (Exception ex1)
                {
                    ApplicationLog.Error("RenewBorrow notice exception", ex1);
                }
            }
            catch (BizException ex)
            {
                response.Message = ex.Message;
            }
            catch (Exception ex)
            {
                response.Message = "提交续借发生异常";
                ApplicationLog.Error("RenewBorrow", ex);
            }
            return(response);
        }
Esempio n. 27
0
 public static void WriteLineAndConsole(string text)
 {
     ApplicationLog.Info(text);
 }
Esempio n. 28
0
        public GenericResponse NewBlockAnnouncement(BlockHeader header)
        {
            try
            {
                if (ApplicationState.ConsensusState != ConsensusStates.WaitingForSpeaker &&
                    ApplicationState.ConsensusState != ConsensusStates.CreatingBlock)
                {
                    return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success));
                }

                //TODO: verify sender signature
                //VerifySignature(callerNode.WalletAddress);

                ApplicationLog.Info("Received new block");

                DataServices dataServices = new DataServices();

                //Validate if sender is current speaker
                if (callerNode.ServerAddress != ApplicationState.CurrentSpeaker.ServerAddress &&
                    callerNode.WalletAddress != ApplicationState.CurrentSpeaker.WalletAddress)
                {
                    ApplicationLog.Info("Speaker Not Recognized");
                    return(new GenericResponse(null, ResponseCodes.SpeakerNotRecognized, ResponseMessages.SpeakerNotRecognized));
                }

                //If first epoch, no need to validate as transactions will unlikely tally due to different start consensus time
                if (ApplicationState.LiveEpochCount == 1 &&
                    ApplicationState.CurrentSpeaker.ServerAddress != ApplicationState.Node.ServerAddress)
                {
                    dataServices.ClearPendingTxUpToId(header.LastTransactionId);
                    return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success));
                }

                //Validate block transactions with local pending transactions
                //Note: If somehow this node received all transactions but not in the correct order, block will be discarded
                //and wait for correction during re-sync in subsequent epochs
                if (header.Hash != dataServices.HashBlockHeaderAndTransactions(header, dataServices.GetPendingTxUpTo(header.LastTransactionId)))
                {
                    //Pending Transaction And Block Mismatch
                    ApplicationLog.Info("Pending Transaction And Block Mismatch");
                    return(new GenericResponse(null, ResponseCodes.PendingTransactionAndBlockMismatch, ResponseMessages.PendingTransactionAndBlockMismatch));
                }

                //Create Block
                var newBlock = dataServices.CreateBlockAndClearPendingTx(header);

                //Attach block fee
                newBlock = dataServices.AttachBlockFee(newBlock, ApplicationState.CurrentSpeaker);

                //Add block to chain
                dataServices.SaveBlockToChain(newBlock);
                ApplicationLog.Info("New block added to chain. Index: " + header.Index);

                return(new GenericResponse(null, ResponseCodes.Success, ResponseMessages.Success));
            }
            catch (Exception ex)
            {
                ApplicationLog.Exception(ex);
                return(new GenericResponse(null, ResponseCodes.Error, ResponseMessages.Error));
            }
            finally
            {
                //Resume next iteration of consensus
                ConsensusServices consensusServices = new ConsensusServices();
                consensusServices.NextEpoch();
            }
        }