private void HandleException(HttpContext httpContext, string referenceNo) { BaseResponseDto <object> baseResponseDto = new BaseResponseDto <object>(); Exception exception = httpContext.Features.Get <IExceptionHandlerFeature>()?.Error; CommonException customExcep = null; if (exception is ValidationException) { customExcep = (ValidationException)exception; } if (exception is PermissionException) { customExcep = (PermissionException)exception; } if (exception is BusinessException) { customExcep = (BusinessException)exception; } if (exception is RepositoryException) { customExcep = (RepositoryException)exception; } if (customExcep != null) { baseResponseDto.ReturnError(customExcep.Result, exception.Message, referenceNo, ((PermissionException)exception).Errors); } httpContext.Response.ContentType = "application/json"; httpContext.Response.StatusCode = (int)HttpStatusCode.OK; httpContext.Response.WriteAsync(baseResponseDto.ToString()); }
// 작업 결과 값을 반환할 경우 CodeActivity<TResult>에서 파생되고 // Execute 메서드에서 값을 반환합니다. protected override void Execute(CodeActivityContext context) { this.ResultBool.Set(context, false); // 텍스트 입력 인수의 런타임 값을 가져옵니다. //string text = context.GetValue(this.Text); List <int> piList = WindowList.GetProcessIdByWindowByTitle(ProcessName, WindowTitle, false); foreach (int pid in piList) { Debug.WriteLine("Found Pid {0}", pid.ToString()); try { Process proc = Process.GetProcessById(pid); proc.Kill(); } catch (ArgumentException ex) { // Process already exited. CommonException.PrintExceptionLog(ex); } } this.ResultBool.Set(context, true); }
public Step ResolveStep(MetadataRule extractedMetadataRule, List <CommonException <StepError> > errors) { var sourceColumn = ResolveColumn(extractedMetadataRule, nameof(extractedMetadataRule.Source), extractedMetadataRule.Source, errors); Regex regex = null; if (!string.IsNullOrEmpty(extractedMetadataRule.Pattern)) { try { regex = new Regex(extractedMetadataRule.Pattern); } catch (Exception x) { errors?.Add(CommonException.Create(new StepError( extractedMetadataRule, nameof(extractedMetadataRule.Pattern), x.Message), x)); } } var targetColumn = ResolveColumn(extractedMetadataRule, nameof(extractedMetadataRule.Target), extractedMetadataRule.Target, errors); return(new Step(extractedMetadataRule, sourceColumn, regex, extractedMetadataRule.Replacement, targetColumn)); }
/// <summary> /// handles cares exception and retrieves culture based message /// </summary> /// <param name="ex"></param> /// <returns></returns> public static string GetCaresExceptionMessage(CommonException ex) { try { if (ex.oExpType == CaresExceptionType.CaresDBForeignKeyVoilateExp) { IstUtilityResourceManager rm = new IstUtilityResourceManager("TableList"); Message = rm.GetValueByKey(ex.ForignKeyTable); return Message; } else if (ex.oExpType == CaresExceptionType.CaresDBExp && ex.InsertUpdateKeyVoilation) { IstUtilityResourceManager rm = new IstUtilityResourceManager("InsertUpdateTableList"); Message = rm.GetValueByKey(ex.ForignKeyTable); return Message; } else { string[] message = ex.Message.Split('-'); IstUtilityResourceManager rm = new IstUtilityResourceManager(message[0]); //Message = ISTUtilityResourceManager.GetConfigMessage(message[0], message[1]); Message = rm.GetValueByKey(message[1]); return Message; } } catch (Exception Ex) { return "There is some problem while performing the operation."; } }
private void RebuildIndex() { var pkColumn = GetColumn(_icolPk); if (pkColumn == null) { _pkIndex = null; return; } var dictionary = new Dictionary <object, int>(pkColumn.RowCount); for (int i = 0; i < pkColumn.RowCount; i++) { var value = pkColumn.GetValue(i); if (null == value) { throw CommonException.Create(ListExceptionDetail.NullValue(ListName, ListDef.IdProperty)); } try { dictionary.Add(pkColumn.GetValue(i), i); } catch (Exception e) { throw CommonException.Create(ListExceptionDetail.DuplicateValue(ListName, ListDef.IdProperty, value), e); } } _pkIndex = dictionary; }
/// <summary> /// 输出为文本。 /// </summary> /// <param name="valueSpliter">key/value分割符。</param> /// <param name="nameSpliter">多个分割符。</param> /// <returns></returns> public string ToString(string valueSpliter, string nameSpliter) { CommonException.CheckArgumentNull(valueSpliter, "valueSpliter"); CommonException.CheckArgumentNull(nameSpliter, "nameSpliter"); System.Text.StringBuilder builder = new System.Text.StringBuilder(); foreach (string name in AllKeys) { string[] values = GetValues(name); if (values == null) { continue; } bool emptyName = string.IsNullOrEmpty(name); foreach (string value in values) { if (builder.Length > 0) { builder.Append(nameSpliter); } if (!emptyName) { builder.Append(name); builder.Append(valueSpliter); } builder.Append(HttpUtility.UrlEncode(value, Encoding)); } } return(builder.ToString()); }
/// <summary> /// 设置IP协议参数。 /// </summary> /// <param name="socket">socket实例,必须在bind之后。</param> /// <param name="level">参数。</param> public static void SetIPProtectionLevel(System.Net.Sockets.Socket socket, System.Net.Sockets.IPProtectionLevel level) { if (level == System.Net.Sockets.IPProtectionLevel.Unspecified) { CommonException.ThrowArgument("无效的level参数:" + level); } if (socket.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { #if net20 || net35 socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.IPv6, (System.Net.Sockets.SocketOptionName) 23, (int)level); #else socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.IPv6, System.Net.Sockets.SocketOptionName.IPProtectionLevel, (int)level); #endif } else { if (socket.AddressFamily != System.Net.Sockets.AddressFamily.InterNetwork) { CommonException.ThrowNotSupported("暂不支持此网络地址类型:" + socket.AddressFamily); } #if net20 || net35 socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.IP, (System.Net.Sockets.SocketOptionName) 23, (int)level); #else socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.IP, System.Net.Sockets.SocketOptionName.IPProtectionLevel, (int)level); #endif } }
/// <summary> /// 创建TcpListener实例。 /// </summary> /// <param name="setting">设置项。</param> public TcpListener(ServerSetting setting) { CommonException.CheckArgumentNull(setting, "setting"); _serverSetting = setting; setting.Readonly = true; _log = LogBase.Empty; }
/// <summary> /// 获取 SQLite.Data 类型 /// </summary> /// <param name="typeFullName">类型全名。</param> /// <param name="throw">是否报错</param> /// <returns></returns> public static System.Type GetType(string typeFullName, bool @throw = false) { var type = SQLite.SQLiteHelper.GetType(typeFullName); if (type == null && @throw) { CommonException.ThrowTypeLoad(typeFullName); } return(type.Type); }
private static Task CommonErrorResult(HttpAuthenticationContext context, CommonException ex) { context.ErrorResult = new ErrorResult { Code = ex.ReasonCode, Message = ex.Message }; return(Task.FromResult(0)); }
public void SetException(Exception exception) { var commonException = exception as CommonException; if (commonException != null) { Exception = commonException; return; } Exception = new CommonException(503, exception.Message, null, null); }
/// <summary> /// 生成求avg命令。 /// </summary> /// <param name="field">字段名称。</param> /// <param name="clear">是否清空所有字段</param> /// <returns></returns> public virtual ISelectCommandBuilder Average(string field, bool clear) { CommonException.CheckArgumentNull(field, "field"); if (clear) { _orderbys.Clear(); _fields.Clear(); } _fields.Add(string.Format("avg({0})", _dialect.PreName(field))); return(this); }
/// <summary> /// 创建数据上下文。 /// </summary> /// <param name="type">数据库提供者名称。</param> /// <param name="connectionOptions">连接参数。</param> /// <returns>返回数据上下文。</returns> public static IDataContext CreateDataContext(string type, object connectionOptions) { CommonException.CheckArgumentNull(type, "type"); var provider = Get(type); if (provider == null) { CommonException.ThrowNotSupported($"未找到数据提供者“{type}”"); } return(provider.CreateDataContext(connectionOptions)); }
/// <summary> /// Errors the specified exception. /// </summary> /// <param name="exception">The exception.</param> /// <param name="index">The index.</param> protected virtual void Error(CommonException exception, string index = "") { if (!string.IsNullOrWhiteSpace(index)) { _log.ErrorFormat("component={0}, action={1}, code={2}, error={3}, index={4}", ComponentName, MethodBase.GetCurrentMethod().Name, exception.ReasonCode, exception.Message, index); } else { _log.ErrorFormat("component={0}, action={1}, code={2}, error={3}", ComponentName, MethodBase.GetCurrentMethod().Name, exception.ReasonCode, exception.Message); } }
public void ApplyRule(MetadataRuleSet ruleSetSet, HashSet <MsDataFileUri> dataFileUris) { var skylineDataSchema = (SkylineDataSchema)_rootColumn.DataSchema; List <Step> resolvedRules = null; foreach (var resultFile in skylineDataSchema.ResultFileList.Values) { if (dataFileUris != null && !dataFileUris.Contains(resultFile.ChromFileInfo.FilePath)) { continue; } if (resolvedRules == null) { var ruleErrors = new List <CommonException <StepError> >(); resolvedRules = new List <Step>(); foreach (var rule in ruleSetSet.Rules) { var resolvedRule = ResolveStep(rule, ruleErrors); if (ruleErrors.Count > 0) { var ruleError = ruleErrors[0]; throw CommonException.Create( new RuleError(ruleSetSet.Name, resultFile.ChromFileInfo.FilePath, ruleError.Message), ruleError); } resolvedRules.Add(resolvedRule); } } var properties = new HashSet <PropertyPath>(); foreach (var rule in resolvedRules) { if (properties.Contains(rule.Def.Target)) { continue; } var result = ApplyStep(resultFile, rule); if (result.ErrorText != null) { throw CommonException.Create(new RuleError(ruleSetSet.Name, resultFile.ChromFileInfo.FilePath, result.ErrorText)); } if (!result.Match) { continue; } properties.Add(rule.Def.Target); rule.Target.SetTextValue(CultureInfo.InvariantCulture, resultFile, result.ReplacedValue); } } }
public ListData ChangeListDef(ListDef newListDef, IDictionary <string, string> originalColumnNames) { if (RowCount == 0 || originalColumnNames != null && originalColumnNames.Count == 0) { return(new ListData(newListDef)); } var newColumns = new List <ColumnData>(); foreach (var annotationDef in newListDef.Properties) { string originalName; if (originalColumnNames == null) { originalName = annotationDef.Name; } else { if (!originalColumnNames.TryGetValue(annotationDef.Name, out originalName)) { newColumns.Add(ColumnData.MakeColumnData(annotationDef).SetRowCount(RowCount)); continue; } } int icolOrig = FindColumnIndex(originalName); var origColumn = Columns[icolOrig]; var origAnnotationDef = ListDef.Properties[icolOrig]; if (annotationDef.ValueType == origAnnotationDef.ValueType) { newColumns.Add(origColumn); continue; } var newColumn = ColumnData.MakeColumnData(annotationDef).SetRowCount(RowCount); for (int i = 0; i < RowCount; i++) { var origValue = origColumn.GetValue(i); object newValue; if (!TryChangeType(origValue, annotationDef.ValueType, out newValue)) { throw CommonException.Create( ListExceptionDetail.InvalidValue(newListDef.Name, origAnnotationDef.Name, origValue)); } if (newValue != null) { newColumn.SetValue(i, newValue); } } newColumns.Add(newColumn); } return(new ListData(newListDef, newColumns)); }
public static Variable NizkCombineFunctionResult(StatementResult result, NType resultNType) { switch (result) { case StatementResultOneCase ret: switch (ret.ExecutionResultType) { case StatementResultType.Continue: case StatementResultType.Break: throw new Exception($"Unexpected \"{ ret.ExecutionResultType.ToString()}\" statement."); case StatementResultType.Normal: case StatementResultType.Return: Debug.Assert((ret.ExecutionResultType != StatementResultType.Normal) || ret.ReturnVariable == null); if (ret.ReturnVariable != null) { return(ret.ReturnVariable.Assign(resultNType)); } if (resultNType == NType.Void) { return(NType.Void.GetEmptyVariable()); } else { throw new Exception("Missing \"return\" statement."); } default: throw CommonException.AssertFailedException(); } case StatementResultTwoCase ret: if (resultNType == NType.Void) { return(NType.Void.GetEmptyVariable()); } var trueVar = NizkCombineFunctionResult(ret.TrueCase, resultNType); var falseVar = NizkCombineFunctionResult(ret.FalseCase, resultNType); return(NizkConditionVariable(ret.Condition, trueVar, falseVar)); default: throw CommonException.AssertFailedException(); } }
private int EnsureFindColumnIndex(string columnName) { if (string.IsNullOrEmpty(columnName)) { return(-1); } int icol = FindColumnIndex(columnName); if (icol < 0) { throw CommonException.Create(ListExceptionDetail.ColumnNotFound(ListName, columnName)); } return(icol); }
/// <summary> /// handles general exception and retrieves culture specific message /// </summary> /// <param name="ex"></param> /// <returns></returns> public static string getExceptionMessage(Exception ex) { try { CommonException Cex = new CommonException(ex.Message, ex); IstUtilityResourceManager rm = new IstUtilityResourceManager("ApplicationExceptions"); Message = rm.GetValueByKey("GeneralException"); return Message; } catch (Exception Ex) { return "There is some problem while performing the operation."; } }
private static CrosslinkLibraryKey.Crosslink ParseCrosslink(string crosslink, int position) { if (!crosslink.StartsWith(@"[")) { throw CommonException.Create(Expected('[', position)); } if (!crosslink.EndsWith(@"]")) { throw CommonException.Create(Expected(']', position + crosslink.Length)); } int ichAt = crosslink.IndexOf('@'); if (ichAt < 0) { throw CommonException.Create(Expected('@', position + crosslink.Length)); } string name = crosslink.Substring(1, ichAt - 1); var indexes = crosslink.Substring(ichAt + 1, crosslink.Length - ichAt - 2); var positionLists = new List <IList <int> >(); foreach (var positions in indexes.Split(',')) { if (positions == @"*") { positionLists.Add(new int[0]); } else { var list = new List <int>(); foreach (var value in positions.Split('-')) { try { list.Add(int.Parse(value, CultureInfo.InvariantCulture)); } catch (Exception) { string message = string.Format(Resources.CrosslinkSequenceParser_ParseCrosslink_Unable_to_parse___0___as_a_number, value); throw CommonException.Create(new ParseExceptionDetail(message, position + ichAt)); } } positionLists.Add(list); } } return(new CrosslinkLibraryKey.Crosslink(name, positionLists)); }
public static void ShowMaxmizeWindow(HWND hWnd) { if (hWnd == IntPtr.Zero) { return; } try { ShowWindow(hWnd, SW_MAXIMIZE); } catch (Exception ex) { CommonException.PrintExceptionLog(ex); } }
private void HandleCommonException(CommonException exception) { switch (exception.ErrorCode) { case ErrorCode.RemoteApiRequestError: MessageBox.Show("An error occurred while receiving data, please try again later."); break; case ErrorCode.RemoteApiNotFoundMovies: MessageBox.Show(exception.Message); break; default: throw new ArgumentOutOfRangeException(nameof(ErrorCode)); } }
private TextColumnWrapper ResolveColumn(MetadataRule rule, string propertyName, PropertyPath propertyPath, List <CommonException <StepError> > errors) { if (propertyPath == null) { return(null); } TextColumnWrapper textColumn; if (!_textColumns.TryGetValue(propertyPath, out textColumn)) { errors?.Add(CommonException.Create(new StepError(rule, propertyName, string.Format(Resources.MetadataExtractor_ResolveColumn_Unable_to_find_column__0_, propertyPath)))); } return(textColumn); }
/// <summary> /// 创建ReferEntry实例 /// </summary> /// <param name="name">名称。</param> /// <param name="source">源。</param> /// <param name="sourceField">源字段。</param> /// <param name="target">目标。</param> /// <param name="targetField">目标字段。</param> public ReferEntry(string name, string source, string sourceField, string target, string targetField) { CommonException.CheckArgumentNull(name, "name"); CommonException.CheckArgumentNull(source, "source"); CommonException.CheckArgumentNull(sourceField, "sourceField"); _name = name; _source = source; _sourceField = sourceField; if (!IsThis) { CommonException.CheckArgumentNull(target, "target"); CommonException.CheckArgumentNull(targetField, "targetField"); _target = target; _targetField = targetField; } }
/// <summary> /// 获取 PostgreSQL.Data 类型 /// </summary> /// <param name="typeFullName">类型全名。</param> /// <param name="throw">是否报错</param> /// <returns></returns> public static System.Type GetType(string typeFullName, bool @throw = false) { if (string.IsNullOrEmpty(typeFullName)) { return(null); } System.Type type = _types[typeFullName]; if (type == null) { string typeName = typeFullName + ", Npgsql"; type = FastWrapper.GetWarpperType(typeName, "Npgsql.dll"); if (type == null && @throw) { CommonException.ThrowTypeLoad(typeName); } _types[typeFullName] = type; } return(type); }
public override void SetValue(object component, object value) { var listItem = (ListItem)component; var newRecord = listItem.GetRecord() as ListItem.NewRecordData; if (newRecord != null) { newRecord.UncommittedValues[AnnotationDef.Name] = value; return; } var existingRecord = listItem.GetRecord() as ListItem.ExistingRecordData; if (existingRecord == null) { throw new InvalidOperationException(@"Invalid row " + listItem.GetRecord()); // Cannot happen } var editDescription = EditDescription.SetAnnotation(AnnotationDef, value) .ChangeElementRef(((ListRef)ListRef.PROTOTYPE.ChangeName(ListName)).GetListItemRef(listItem)); SkylineDataSchema.ModifyDocument(editDescription, doc => { var listInfo = GetListInfo(doc); if (listInfo == null) { throw new InvalidOperationException(Resources.ListColumnPropertyDescriptor_SetValue_List_has_been_deleted); } if (listInfo.ColumnIndex < 0) { throw CommonException.Create(ListExceptionDetail.ColumnNotFound(ListName, AnnotationDef.Name)); } int rowIndex = listInfo.ListData.RowIndexOf(existingRecord.ListItemId); if (rowIndex < 0) { throw new ArgumentException(Resources.ListColumnPropertyDescriptor_SetValue_List_item_has_been_deleted_); } var listData = listInfo.ListData; listData = listData.ChangeColumn(listInfo.ColumnIndex, listData.Columns[listInfo.ColumnIndex].SetValue(rowIndex, value)); return(doc.ChangeSettings( doc.Settings.ChangeDataSettings( ChangeListData(doc.Settings.DataSettings, listData)))); }, AuditLogEntry.SettingsLogFunction); }
/// <summary> /// 解密指定的数据(文本,UTF8编码)。 /// </summary> /// <param name="text">需要解密的文本。</param> /// <param name="key">key。</param> /// <param name="vector">vector。</param> /// <returns>返回解密后的数据。</returns> public static string Decrypt(string text, string key, string vector) { if (string.IsNullOrEmpty(text)) { return(text); } if (text.Length % 2 != 0) { CommonException.ThrowArgument("text"); } //throw new EncryptTextNotSymmetryException(); //byte[] array = new byte[text.Length / 2]; //for (int i = 0, j = 0; i < text.Length; i += 2, j++) { // array[j] = byte.Parse(text.Substring(i, 2), System.Globalization.NumberStyles.AllowHexSpecifier); //} byte[] bResult = Decrypt(ByteExtensions.HexToBytes(text), key, vector); return(System.Text.Encoding.UTF8.GetString(bResult)); }
public override unsafe BleEvent ReadEvent() { HandleAcquireIfOpenOrFail(); try { while (true) { IntPtr *handles = stackalloc IntPtr[2]; handles[0] = _watchEventHandle; handles[1] = _closeEventHandle; uint waitResult = NativeMethods.WaitForMultipleObjects(2, handles, false, NativeMethods.WaitForMultipleObjectsGetTimeout(ReadTimeout)); switch (waitResult) { case NativeMethods.WAIT_OBJECT_0: break; case NativeMethods.WAIT_OBJECT_1: throw CommonException.CreateClosedException(); default: throw new TimeoutException(); } lock (_watchSync) { // We *may* have multiple threads calling ReadEvent(). Another thread may have read the event. // FIXME: If so, the timeout is not going to operate correctly here. if (_watchEvents.Count == 0) { NativeMethods.ResetEvent(_watchEventHandle); continue; } var @event = _watchEvents.Dequeue(); if (_watchEvents.Count == 0) { NativeMethods.ResetEvent(_watchEventHandle); } return(@event); } } } finally { HandleRelease(); } }
/// <summary> /// 解析key/value。 /// </summary> /// <param name="values">包含key/value的文本</param> /// <param name="needDecode">是否需要解码</param> /// <param name="separator">分割符</param> public void ParseValues(string values, bool needDecode, params string[] separator) { if (separator == null || separator.Length == 0) { CommonException.ThrowArgumentNull("separator"); } if (string.IsNullOrEmpty(values)) { return; } if (values.StartsWith("?")) { values = values.Substring(1); } var keys = new Symbol.Collections.Generic.HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (string item in values.Split(separator, StringSplitOptions.None)) { string key = string.Empty; string value = string.Empty; if (item.IndexOf('=') == -1) { value = item; } else { string[] array = item.Split('='); key = array[0]; value = array[1]; } if (keys.Add(key)) { this.Remove(key); } Add(key, needDecode ? HttpUtility.UrlDecode(value, Encoding) : value); } }
public static CrosslinkLibraryKey ParseCrosslinkLibraryKey(string str, int charge) { List <PeptideLibraryKey> peptideSequences = new List <PeptideLibraryKey>(); List <CrosslinkLibraryKey.Crosslink> crosslinks = new List <CrosslinkLibraryKey.Crosslink>(); bool inCrosslinkers = false; int ich = 0; foreach (var token in Tokenize(str)) { if (token.StartsWith(@"[") && token.EndsWith(@"]")) { inCrosslinkers = true; } if (inCrosslinkers) { crosslinks.Add(ParseCrosslink(token, ich)); } else { string sequence = token; if (sequence.EndsWith(@"-")) { sequence = sequence.Substring(sequence.Length - 1); } if (!FastaSequence.IsExSequence(sequence)) { throw CommonException.Create(new ParseExceptionDetail(Resources.CrosslinkSequenceParser_ParseCrosslinkLibraryKey_Invalid_peptide_sequence, ich)); } peptideSequences.Add(new PeptideLibraryKey(sequence, 0)); } ich += token.Length; } return(new CrosslinkLibraryKey(peptideSequences, crosslinks, charge)); }
/// <summary> /// 创建数据库连接。 /// </summary> /// <param name="connectionString">连接字符串。</param> /// <returns>返回数据库连接。</returns> public override IConnection CreateConnection(string connectionString) { CommonException.CheckArgumentNull(connectionString, "connectionString"); System.Type type = GetConnectionType(true); return(new PostgreSQLConnection(this, FastWrapper.CreateInstance <IDbConnection>(type, connectionString), connectionString)); }
static Exception ExceptionForClosed() { return(CommonException.CreateClosedException()); }
public void OutputCircuit(TextWriter arithWriter, TextWriter inHelperWriter) { var wireToID = new Dictionary <PinocchioWire, int>(); void AddWire(PinocchioWire wire) { if (wireToID.ContainsKey(wire)) { return; } wireToID.Add(wire, wireToID.Keys.Count); } var conList = new List <IPinocchioConstraint>(); void AddConstraint(IPinocchioConstraint con) { conList.Add(con); } var rawVarToWires = new Dictionary <RawVariable, PinocchioVariableWires>(); void AddVariableWires(PinocchioVariableWires variableWires) { if (rawVarToWires.ContainsKey(variableWires.RawVariable)) { return; } rawVarToWires.Add(variableWires.RawVariable, variableWires); variableWires.Wires.ForEach(AddWire); } void AddPinocchioSubOutput(PinocchioSubOutput ret) { AddVariableWires(ret.VariableWires); ret.AnonymousWires.ForEach(AddWire); ret.Constraints.ForEach(AddConstraint); } var commonArg = new PinocchioCommonArg(); { // 1 { commonArg.OneWire = new PinocchioWire(); AddWire(commonArg.OneWire); var comment = new CommentConstraint(); AddConstraint(comment); comment.Comment = "The constant wire, value 1"; var con = new ConstWireConstraint(); AddConstraint(con); con.ConstVariableWires = new PinocchioVariableWires( NType.Field.GetCommonConstantValue(VariableCommonConstant.One).RawVariable, commonArg.OneWire); } // 0 { commonArg.ZeroWire = new PinocchioWire(); AddWire(commonArg.ZeroWire); var comment = new CommentConstraint(); AddConstraint(comment); comment.Comment = "The constant wire, value 0"; var con = new ConstWireConstraint(); AddConstraint(con); con.ConstVariableWires = new PinocchioVariableWires( NType.Field.GetCommonConstantValue(VariableCommonConstant.Zero).RawVariable, commonArg.ZeroWire); } // -1 { commonArg.MinusOneWire = new PinocchioWire(); AddWire(commonArg.MinusOneWire); var comment = new CommentConstraint(); AddConstraint(comment); comment.Comment = "The constant wire, value -1"; var con = new ConstWireConstraint(); AddConstraint(con); con.ConstVariableWires = new PinocchioVariableWires( NType.Field.GetCommonConstantValue(VariableCommonConstant.MinusOne).RawVariable, commonArg.MinusOneWire); } // 2 commonArg.PowerOfTwoWires = new PinocchioWire[My.Config.ModulusPrimeField_Prime_Bit + 1]; commonArg.PowerOfTwoWires[0] = commonArg.OneWire; var powerOfTwoBaseVariable = NType.Field.GetCommonConstantValue(VariableCommonConstant.One); foreach (int i in Enumerable.Range(1, My.Config.ModulusPrimeField_Prime_Bit)) { commonArg.PowerOfTwoWires[i] = new PinocchioWire(); AddWire(commonArg.PowerOfTwoWires[i]); powerOfTwoBaseVariable = NType.Field.BinaryOperation( powerOfTwoBaseVariable, powerOfTwoBaseVariable, VariableOperationType.Binary_Addition); var comment = new CommentConstraint(); AddConstraint(comment); comment.Comment = $"The constant wire, value (base 10) 2^{i.ToString(CultureInfo.InvariantCulture)}"; var con = new ConstWireConstraint(); AddConstraint(con); con.ConstVariableWires = new PinocchioVariableWires(powerOfTwoBaseVariable.RawVariable, commonArg.PowerOfTwoWires[i]); //todo: bug: the value of 2^254 is not correct. Figure out why. } } var outputVariableWiresDict = new Dictionary <RawVariable, (PinocchioTypeWires TypeWires, string VarName)>(); void AddOutputVariableWires(PinocchioVariableWires variableWires, string varName) { if (!outputVariableWiresDict.ContainsKey(variableWires.RawVariable)) { outputVariableWiresDict.Add(variableWires.RawVariable, (TypeWires: new PinocchioTypeWires(variableWires), VarName: varName)); } else { Debug.Assert(varName == outputVariableWiresDict[variableWires.RawVariable].VarName); Debug.Assert(variableWires.Wires.SequenceEqual(outputVariableWiresDict[variableWires.RawVariable].TypeWires.Wires)); } } foreach (var node in this.VariableMap.TopologicalSort()) { switch (node) { case VariableNode variableNode: // a variable node is either an input/nizk/constant node, which is NOT produced by constraints // or a non-constant intermediate/output node, which has already been produced by constraints PinocchioVariableWires outputVarWires = null; if (!rawVarToWires.ContainsKey(variableNode.RawVariable)) { // new wire(s) Debug.Assert( ((variableNode.NizkAttribute == NizkVariableType.Intermediate || variableNode.NizkAttribute == NizkVariableType.Output) && variableNode.RawVariable.Value.IsConstant) || variableNode.NizkAttribute == NizkVariableType.Input || variableNode.NizkAttribute == NizkVariableType.NizkInput); if (variableNode.RawVariable.Value.IsConstant) { var output = variableNode.RawVariable.Type.VariableNodeToPinocchio(variableNode.RawVariable, commonArg, false); AddPinocchioSubOutput(output); { var comment = new CommentConstraint(); AddConstraint(comment); comment.Comment = $"The following {output.VariableWires.Wires.Count.ToString(CultureInfo.InvariantCulture)} wires are of a constant value (base 10) {variableNode.RawVariable.Type.GetVariableString(variableNode.RawVariable)}."; var con = new ConstWireConstraint(); AddConstraint(con); con.ConstVariableWires = output.VariableWires; } if (variableNode.NizkAttribute == NizkVariableType.Output) { outputVarWires = output.VariableWires; } // obsolete: mul by one is handled later //// if the output variable is also constant, mul by one as new outputs //if (variableNode.NizkAttribute == NizkVariableType.Output) //{ // List<PinocchioWire> outputWires = new List<PinocchioWire>(); // foreach (var wire in output.VariableWires.Wires) // { // var newWire = new PinocchioWire(); // AddWire(newWire); // var newCon = new BasicPinocchioConstraint(BasicPinocchioConstraintType.Mul); // AddConstraint(newCon); // newCon.InWires.Add(wire); // newCon.InWires.Add(commonArg.OneWire); // newCon.OutWires.Add(newWire); // outputWires.Add(newWire); // } // outputVarWires = new PinocchioVariableWires(variableNode.RawVariable, outputWires); //} } else { switch (variableNode.NizkAttribute) { // policy: checkRange is applied for nizkinput, and not applied for others case NizkVariableType.NizkInput: { var comment = new CommentConstraint(); AddConstraint(comment); var con = new UserPrivateInputConstraint(); AddConstraint(con); var output = variableNode.RawVariable.Type.VariableNodeToPinocchio(variableNode.RawVariable, commonArg, true); AddPinocchioSubOutput(output); comment.Comment = $"The following {output.VariableWires.Wires.Count.ToString(CultureInfo.InvariantCulture)} wires are nizk-input wires of variable \"{variableNode.VarName}\"."; con.TypeWires = new PinocchioTypeWires(output.VariableWires); break; } case NizkVariableType.Input: { var output = variableNode.RawVariable.Type.VariableNodeToPinocchio(variableNode.RawVariable, commonArg, false); AddPinocchioSubOutput(output); var comment = new CommentConstraint(); AddConstraint(comment); comment.Comment = $"The following {output.VariableWires.Wires.Count.ToString(CultureInfo.InvariantCulture)} wires are input wires of variable \"{variableNode.VarName}\"."; var con = new UserInputConstraint(); AddConstraint(con); con.TypeWires = new PinocchioTypeWires(output.VariableWires); break; } default: throw CommonException.AssertFailedException(); } } } else { // old wire(s) Debug.Assert(variableNode.NizkAttribute == NizkVariableType.Intermediate || variableNode.NizkAttribute == NizkVariableType.Output); Debug.Assert(!variableNode.RawVariable.Value.IsConstant); if (variableNode.NizkAttribute == NizkVariableType.Output) { outputVarWires = rawVarToWires[variableNode.RawVariable]; } } if (outputVarWires != null) { AddOutputVariableWires(outputVarWires, variableNode.VarName); } break; case OperationNode operationNode: // get all in-variable List <PinocchioVariableWires> inVars = new List <PinocchioVariableWires>(); foreach (var prevNode in operationNode.PrevNodes) { var varNode = (VariableNode)prevNode; Debug.Assert(rawVarToWires.ContainsKey(varNode.RawVariable)); inVars.Add(rawVarToWires[varNode.RawVariable]); } // currently, assume at least one inVar Debug.Assert(inVars.Count >= 1); // for every outputVar, produce new PinocchioOutput according to the operation foreach (var outNode in operationNode.NextNodes) { var outVarNode = (VariableNode)outNode; PinocchioSubOutput output = inVars[0].RawVariable.Type.OperationNodeToPinocchio( operationNode.ConnectionType, inVars, outVarNode.RawVariable, commonArg ); AddPinocchioSubOutput(output); } break; default: throw CommonException.AssertFailedException(); } } // todo: optimize redundancy wire & constraints // note: even if all the output of some constraints are not used, it is NOT considered useless // example here: input 1; split in 1 <1> out 32 <2,3,4,...,33>; this constraint ensure that "input 1" is smaller than 2^32, and must not be deleted while optimizing // declare the output wires at the end foreach (var(_, (typeWires, varName)) in outputVariableWiresDict) { var newTypeWires = new PinocchioTypeWires(); newTypeWires.Type = typeWires.Type; // mul by 1 foreach (var wire in typeWires.Wires) { var newWire = new PinocchioWire(); AddWire(newWire); var con = new BasicPinocchioConstraint(BasicPinocchioConstraintType.Mul); AddConstraint(con); con.InWires.Add(wire); con.InWires.Add(commonArg.OneWire); con.OutWires.Add(newWire); newTypeWires.Wires.Add(newWire); // ReSharper disable once UseIndexFromEndExpression Debug.Assert(typeWires.Wires[newTypeWires.Wires.Count - 1] == wire); } { var comment = new CommentConstraint(); AddConstraint(comment); comment.Comment = $"The following {newTypeWires.Wires.Count.ToString(CultureInfo.InvariantCulture)} wires are output wires of variable \"{varName}\"."; } { var con = new OutputConstraint(); AddConstraint(con); con.TypeWires = newTypeWires; } } // write these wire & constraints arithWriter.WriteLine("total " + (wireToID.Keys.Count.ToString(CultureInfo.InvariantCulture))); foreach (var constraint in conList) { switch (constraint) { case BasicPinocchioConstraint basicPinocchioConstraint: StringBuilder sb = new StringBuilder(); _ = basicPinocchioConstraint.Type switch { BasicPinocchioConstraintType.Add => sb.Append("add"), BasicPinocchioConstraintType.Mul => sb.Append("mul"), BasicPinocchioConstraintType.Or => sb.Append("or"), BasicPinocchioConstraintType.Pack => sb.Append("pack"), BasicPinocchioConstraintType.Split => sb.Append("split"), BasicPinocchioConstraintType.Xor => sb.Append("xor"), BasicPinocchioConstraintType.ZeroP => sb.Append("zerop"), _ => throw CommonException.AssertFailedException(), }; // zerop compatibility if (basicPinocchioConstraint.Type == BasicPinocchioConstraintType.ZeroP && basicPinocchioConstraint.OutWires.Count == 1) { basicPinocchioConstraint.OutWires.Insert(0, commonArg.OneWire); } // zerop compatibility end _ = sb.Append(" in "); _ = sb.Append(basicPinocchioConstraint.InWires.Count.ToString(CultureInfo.InvariantCulture)); _ = sb.Append(" <"); foreach (var wire in basicPinocchioConstraint.InWires) { _ = sb.Append(" " + wireToID[wire].ToString(CultureInfo.InvariantCulture)); } _ = sb.Append(" > out "); _ = sb.Append(basicPinocchioConstraint.OutWires.Count.ToString(CultureInfo.InvariantCulture)); _ = sb.Append(" <"); foreach (var wire in basicPinocchioConstraint.OutWires) { _ = sb.Append(" " + wireToID[wire].ToString(CultureInfo.InvariantCulture)); } _ = sb.Append(" >"); arithWriter.WriteLine(sb.ToString()); break; case UserInputConstraint userInputConstraint: Debug.Assert(userInputConstraint.TypeWires.Wires.Count != 0); userInputConstraint.TypeWires.Wires.ForEach(wire => arithWriter.WriteLine("input " + wireToID[wire] + " #userinput")); userInputConstraint.TypeWires.Wires.ForEach(wire => inHelperWriter.WriteLine(wireToID[wire] + " <to-be-filled-by-user, base 16>")); break; case UserPrivateInputConstraint userPrivateInputConstraint: Debug.Assert(userPrivateInputConstraint.TypeWires.Wires.Count != 0); userPrivateInputConstraint.TypeWires.Wires.ForEach(wire => arithWriter.WriteLine("nizkinput " + wireToID[wire] + " #userinput")); userPrivateInputConstraint.TypeWires.Wires.ForEach(wire => inHelperWriter.WriteLine(wireToID[wire] + " <to-be-filled-by-user, base 16>")); break; case OutputConstraint outputConstraint: Debug.Assert(outputConstraint.TypeWires.Wires.Count != 0); outputConstraint.TypeWires.Wires.ForEach(wire => arithWriter.WriteLine("output " + wireToID[wire] + " #output")); break; case ConstWireConstraint constWireConstraint: Debug.Assert(constWireConstraint.ConstVariableWires.Wires.Count != 0); constWireConstraint.ConstVariableWires.Wires.ForEach(wire => arithWriter.WriteLine("input " + wireToID[wire] + " #const")); if (constWireConstraint.ConstVariableWires.Wires.Count == 1) { constWireConstraint.ConstVariableWires.Wires.ForEach(wire => inHelperWriter.WriteLine(wireToID[wire] + " " + constWireConstraint.ConstVariableWires.RawVariable.Type.GetVariableInt(constWireConstraint.ConstVariableWires.RawVariable).ToString("X", CultureInfo.InvariantCulture))); } else { constWireConstraint.ConstVariableWires.Wires.ForEach(wire => inHelperWriter.WriteLine(wireToID[wire] + " <todo-multiple-wires-constant>")); } break; case CommentConstraint commentConstraint: arithWriter.WriteLine("#" + commentConstraint.Comment); break; case DivModConstraint divModConstraint: //todo throw new NotImplementedException(); default: throw CommonException.AssertFailedException(); } } // congrats! }