Exemple #1
0
 public override Task <AuthReply> RefreshToken(AuthRequest request, ServerCallContext context)
 {
     try
     {
         //data 没有token 标识是login判断 能进来就表示client端已连接
         if (string.IsNullOrEmpty(request.Data))
         {
             return(Task.FromResult(new AuthReply()
             {
                 Status = true
             }));
         }
         //data 有数据 并且该数据是token ,根据token找到CA证书,重新生成token返回
         //用现有的token刷新
         var rs = _cache.TryGetValue(RSAHelper.GenerateMD5(request.Data), out Certificate ca);
         if (rs)
         {
             var token = CreateToken(ca);
             return(Task.FromResult(new AuthReply()
             {
                 Status = true,
                 Token = token,
             }));
         }
         else
         {
             return(Task.FromResult(new AuthReply()
             {
                 Status = false,
             }));
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, ex.Message);
         return(Task.FromResult(new AuthReply()
         {
             Status = false,
             Msg = ex.Message
         }));
     }
 }
Exemple #2
0
 /// <summary>
 /// 签名校验通过后 返回token
 /// </summary>
 /// <param name="request"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public override Task <AuthReply> GetToken(AuthRequest request, ServerCallContext context)
 {
     try
     {
         var rs = _cache.TryGetValue(request.CaNumber, out Certificate ca);
         if (!rs)
         {
             return(Task.FromResult(new AuthReply()
             {
                 Status = false
             }));
         }
         //验证签名
         var verifyRs = RSAHelper.VerifyData(ca.TBSCertificate.PublicKey, ca.SignatureValue, request.Data);
         if (!verifyRs)
         {
             return(Task.FromResult(new AuthReply()
             {
                 Status = false
             }));
         }
         _cache.Remove(request.CaNumber);
         var token = CreateToken(ca);
         //30分钟有效
         _cache.Set(RSAHelper.GenerateMD5(token), ca, TimeSpan.FromSeconds(30 * 60));
         return(Task.FromResult(new AuthReply()
         {
             Status = true,
             Token = token
         }));
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, ex.Message);
         return(Task.FromResult(new AuthReply()
         {
             Status = false,
             Msg = ex.Message
         }));
     }
 }
Exemple #3
0
        /// <summary>
        /// 创建新通道 默认只加载本地的节点
        /// </summary>
        /// <param name="channelName"></param>
        public async Task <TxResponse> CreateNewChannel(string channelId)
        {
            //创建交易请求
            var txHeader = new TxHeader();

            txHeader.ChannelId     = channelId;
            txHeader.Type          = TxType.Invoke;
            txHeader.ChaincodeName = ConfigKey.SysNetConfigChaincode;
            txHeader.FuncName      = ConfigKey.InitChannelFunc;
            txHeader.Args          = new string[] { channelId };

            var tx = ModelHelper.ToTxRequest(txHeader);

            EndorseResponse response = new EndorseResponse();
            var             result   = ChainCodeSubmit(tx).Result;

            if (result.StatusCode != StatusCode.Successful)
            {
                return(new TxResponse()
                {
                    Status = false, Msg = result.Message
                });
            }
            response.TxReadWriteSet       = result.TxReadWriteSet;
            response.Status               = true;
            response.Msg                  = "背书完成";
            response.Endorsement.Identity = _configProvider.GetPublicIndentity();
            var str        = Newtonsoft.Json.JsonConvert.SerializeObject(response);
            var privatekey = _configProvider.GetPrivateKey();

            //节点对背书数据签名
            response.Endorsement.Signature = RSAHelper.SignData(privatekey, response);

            Envelope envelope = new Envelope();

            envelope.TxReqeust = tx;
            envelope.Endorsements.Add(response.Endorsement);
            envelope.PayloadReponse                = new ProposaResponsePayload();
            envelope.PayloadReponse.Message        = response.Msg;
            envelope.PayloadReponse.Status         = response.Status;
            envelope.PayloadReponse.TxReadWriteSet = response.TxReadWriteSet;

            var block = new Block();

            block.Header.ChannelId = channelId;
            block.Header.Number    = 0;
            block.Header.Term      = 0;
            block.Header.Timestamp = DateTime.Now.Ticks;
            block.Data.Envelopes.Add(envelope);
            block.Signer.Identity = _configProvider.GetPublicIndentity();
            //计算hash·
            block.Header.DataHash = RSAHelper.GenerateMD5(Newtonsoft.Json.JsonConvert.SerializeObject(block));
            //对整个区块进行签名
            block.Signer.Signature = RSAHelper.SignData(_configProvider.GetPrivateKey(), block);
            //上链
            await _dataManager.PutOnChainBlockAsync(block);

            return(new TxResponse()
            {
                Status = true
            });
        }
Exemple #4
0
        /// <summary>
        /// 打包
        /// </summary>
        private void BlockPacking()
        {
            try
            {
                _timer.Change(Timeout.Infinite, Timeout.Infinite);
                lock (packing)
                {
                    //对交易进行排序
                    List <Envelope> data = null;
                    lock (obj)
                    {
                        if (_txList.Count == 0)
                        {
                            return;
                        }
                        data = _txList.Where(p => true).ToList();
                        _txList.Clear();
                    }

                    #region 组装区块数据
                    //var txmq = new Msg.Imp.TxMQ(_configProvider.GetMQSetting());

                    var currentBlock = _blockDataManager.GetLastBlock(_node.GetChannelId());
                    var block        = new Block();
                    block.Signer.Identity = _configProvider.GetPeerIdentity().GetPublic();
                    //交易验证
                    data = Validate(data);
                    //错误交易发送
                    //txmq.PublishTxResponse(errorTx, "交易失败");

                    block.Data.Envelopes   = data;
                    block.Header.Timestamp = DateTime.Now.Ticks;
                    block.Header.Number    = currentBlock.Header.Number + 1;
                    block.Header.ChannelId = _node.GetChannelId();
                    //Term
                    block.Header.PreviousHash = currentBlock.Header.DataHash;
                    block.Header.DataHash     = RSAHelper.GenerateMD5(Newtonsoft.Json.JsonConvert.SerializeObject(block));
                    block.Signer.Signature    = RSAHelper.SignData(_configProvider.GetPrivateKey(), block);

                    #endregion

                    #region 区块分发

                    Concensus.Messages.HandOutResponse ts = null;
                    try
                    {
                        _log.LogWarning("区块分发开始");
                        ts = _node.BlockHandOut(block).Result;
                        _log.LogWarning("区块分发结束");
                    }
                    catch (Exception ex)
                    {
                        ts = new Concensus.Messages.HandOutResponse
                        {
                            Message = ex.Message,
                            Success = false
                        };
                        _log.LogWarning("区块分发错误");
                        _log.LogError(ex, ex.Message);
                    }

                    #endregion

                    #region  链结果消息发送

                    foreach (var item in block.Data.Envelopes)
                    {
                        _memoryCache.Set("tx_" + item.TxReqeust.Data.TxId, ts.Success ? "1" : "2", TimeSpan.FromMinutes(10));
                    }

                    //if (ts.Success)
                    //{
                    //    //txmq.PublishTxResponse(block, null);
                    //}
                    //else
                    //{
                    //    //txmq.PublishTxResponse(block, ts.Message);
                    //}

                    /*
                     * if (ts.Success)
                     * {
                     *  foreach (var item in block.Data.Envelopes)
                     *  {
                     *      //
                     *      // _txStatus.Add(item.TxReqeust.Data.TxId, true);
                     *  }
                     * }
                     * else
                     * {
                     *  //通知  block中的交易失败
                     *  foreach (var item in block.Data.Envelopes)
                     *  {
                     *      _txStatus.Add(item.TxReqeust.Data.TxId, false);
                     *  }
                     * }
                     */
                    #endregion
                }
            }
            catch (Exception ex)
            {
                _log.LogError(ex, ex.Message);
            }
            finally
            {
                _timer.Change(_configProvider.GetBatchTimeout(), _configProvider.GetBatchTimeout());
            }
        }