public void TestAbs() { var value = new BigInteger(-50); var absolute = value.Abs(); Assert.AreEqual(new BigInteger(50), absolute); }
public virtual ECPoint Multiply(ECPoint p, BigInteger k) { int sign = k.SignValue; if (sign == 0 || p.IsInfinity) return p.Curve.Infinity; ECPoint positive = MultiplyPositive(p, k.Abs()); return sign > 0 ? positive : positive.Negate(); }
/** @see BigInteger#ToDouble() */ public static double BigInteger2Double(BigInteger val) { // val.bitLength() < 64 if ((val.numberLength < 2) || ((val.numberLength == 2) && (val.Digits[1] > 0))) { return val.ToInt64(); } // val.bitLength() >= 33 * 32 > 1024 if (val.numberLength > 32) { return ((val.Sign > 0) ? Double.PositiveInfinity : Double.NegativeInfinity); } int bitLen = val.Abs().BitLength; long exponent = bitLen - 1; int delta = bitLen - 54; // We need 54 top bits from this, the 53th bit is always 1 in lVal. long lVal = val.Abs().ShiftRight(delta).ToInt64(); /* * Take 53 bits from lVal to mantissa. The least significant bit is * needed for rounding. */ long mantissa = lVal & 0x1FFFFFFFFFFFFFL; if (exponent == 1023) { if (mantissa == 0X1FFFFFFFFFFFFFL) { return ((val.Sign > 0) ? Double.PositiveInfinity : Double.NegativeInfinity); } if (mantissa == 0x1FFFFFFFFFFFFEL) { return ((val.Sign > 0) ? Double.MaxValue : -Double.MaxValue); } } // Round the mantissa if (((mantissa & 1) == 1) && (((mantissa & 2) == 2) || BitLevel.NonZeroDroppedBits(delta, val.Digits))) { mantissa += 2; } mantissa >>= 1; // drop the rounding bit // long resSign = (val.sign < 0) ? 0x8000000000000000L : 0; long resSign = (val.Sign < 0) ? Int64.MinValue : 0; exponent = ((1023 + exponent) << 52) & 0x7FF0000000000000L; long result = resSign | exponent | mantissa; return BitConverter.Int64BitsToDouble(result); }
protected virtual BigInteger CalculateB(BigInteger k, BigInteger g, int t) { bool negative = (g.SignValue < 0); BigInteger b = k.Multiply(g.Abs()); bool extra = b.TestBit(t - 1); b = b.ShiftRight(t); if (extra) { b = b.Add(BigInteger.One); } return negative ? b.Negate() : b; }
public virtual ECPoint Multiply(ECPoint p, BigInteger k) { int sign = k.SignValue; if (sign == 0 || p.IsInfinity) return p.Curve.Infinity; ECPoint positive = MultiplyPositive(p, k.Abs()); ECPoint result = sign > 0 ? positive : positive.Negate(); /* * Although the various multipliers ought not to produce invalid output under normal * circumstances, a final check here is advised to guard against fault attacks. */ return ECAlgorithms.ValidatePoint(result); }
/** * Simple shift-and-add multiplication. Serves as reference implementation * to verify (possibly faster) implementations, and for very small scalars. * * @param p * The point to multiply. * @param k * The multiplier. * @return The result of the point multiplication <code>kP</code>. */ public static ECPoint ReferenceMultiply(ECPoint p, BigInteger k) { BigInteger x = k.Abs(); ECPoint q = p.Curve.Infinity; int t = x.BitLength; if (t > 0) { if (x.TestBit(0)) { q = p; } for (int i = 1; i < t; i++) { p = p.Twice(); if (x.TestBit(i)) { q = q.Add(p); } } } return k.SignValue < 0 ? q.Negate() : q; }
//Ро- метод Полларда public static List <BigInteger> PollardsAlg(BigInteger n) { var result = new List <BigInteger>(); if (BigIntegerPrimeTest.MillerRabinTest(n)) { return(result); } BigInteger N = n; BigInteger i = 1; BigInteger nextiToSave = 1; Random rand = new Random(); BigInteger x = RandomBigInteger(n, rand); BigInteger y = 1, lastx = 1; BigInteger res = 0; while (N % 2 == 0) { if (!result.Contains(2)) { result.Add(2); } N /= 2; } while (!BigIntegerPrimeTest.MillerRabinTest(N)) { BigInteger factor; BigInteger delta = BigInteger.Abs(x - y); if (delta == 0) { x = RandomBigInteger(n, rand); i = 0; nextiToSave = 1; y = 1; lastx = 1; continue; } BigInteger gcd = BigInteger.GreatestCommonDivisor(N, delta); lastx = x; x = (x * x - 1) % n; if (i == nextiToSave) { nextiToSave *= 2; y = lastx; } i++; if (gcd > 1) { factor = gcd; if (!BigIntegerPrimeTest.MillerRabinTest(factor)) { var factorFactors = PollardsAlg(factor); foreach (var item in factorFactors) { result.Add(item); } } else { if (factor > 1) { result.Add(factor); } } N /= factor; } } if (N > 1 && !result.Contains(N)) { result.Add(N); } result.Sort(); return(result); }
public static string ToWords(this BigInteger number) { /* * Convert A Number into Words * by Richard Carr, published at http://www.blackwasp.co.uk/numbertowords.aspx */ /* * Zero Rule. * If the value is 0 then the number in words is 'zero' and no other rules apply. */ if (number == 0) { return("zero"); } /* * Three Digit Rule. * The integer value is split into groups of three digits starting from the * right-hand side. Each set of three digits is then processed individually * as a number of hundreds, tens and units. Once converted to text, the * three-digit groups are recombined with the addition of the relevant scale * number (thousand, million, billion). */ // Array to hold the specified number of three-digit groups int[] digitGroups = new int[groups]; // Ensure a positive number to extract from var positive = BigInteger.Abs(number); // Extract the three-digit groups for (int i = 0; i < groups; i++) { digitGroups[i] = (int)(positive % 1000); positive /= 1000; } // write to a text file in the project folder Trace.Listeners.Add(new TextWriterTraceListener( File.AppendText("log.txt"))); // text writer is buffered, so this option calls // Flush() on all listeners after writing Trace.AutoFlush = true; // log array of group numbers for (int x = 0; x < digitGroups.Length; x++) { Trace.WriteLine(string.Format( format: "digitGroups[{0}] = {1}", arg0: x, arg1: digitGroups[x])); } // Convert each three-digit group to words string[] groupTexts = new string[groups]; for (int i = 0; i < groups; i++) { // call a local function (see below) groupTexts[i] = ThreeDigitGroupToWords(digitGroups[i]); } // log array of group texts for (int x = 0; x < groupTexts.Length; x++) { Trace.WriteLine(string.Format( format: "groupTexts[{0}] = {1}", arg0: x, arg1: groupTexts[x])); } /* * Recombination Rules. * When recombining the translated three-digit groups, each group except the * last is followed by a large number name and a comma, unless the group is * blank and therefore not included at all. One exception is when the final * group does not include any hundreds and there is more than one non-blank * group. In this case, the final comma is replaced with 'and'. eg. * 'one billion, one million and twelve'. */ // Recombine the three-digit groups string combined = groupTexts[0]; bool appendAnd; // Determine whether an 'and' is needed appendAnd = (digitGroups[0] > 0) && (digitGroups[0] < 100); // Process the remaining groups in turn, smallest to largest for (int i = 1; i < groups; i++) { // Only add non-zero items if (digitGroups[i] != 0) { // Build the string to add as a prefix string prefix = groupTexts[i] + " " + scaleNumbers[i]; if (combined.Length != 0) { prefix += appendAnd ? " and " : ", "; } // Opportunity to add 'and' is ended appendAnd = false; // Add the three-digit group to the combined string combined = prefix + combined; } } // Converts a three-digit group into English words string ThreeDigitGroupToWords(int threeDigits) { // Initialise the return text string groupText = ""; // Determine the hundreds and the remainder int hundreds = threeDigits / 100; int tensUnits = threeDigits % 100; /* * Hundreds Rules. * If the hundreds portion of a three-digit group is not zero, the number of * hundreds is added as a word. If the three-digit group is exactly divisible * by one hundred, the text 'hundred' is appended. If not, the text * "hundred and" is appended. eg. 'two hundred' or 'one hundred and twelve' */ if (hundreds != 0) { groupText += smallNumbers[hundreds] + " hundred"; if (tensUnits != 0) { groupText += " and "; } } // Determine the tens and units int tens = tensUnits / 10; int units = tensUnits % 10; /* Tens Rules. * If the tens section of a three-digit group is two or higher, the appropriate * '-ty' word (twenty, thirty, etc.) is added to the text and followed by the * name of the third digit (unless the third digit is a zero, which is ignored). * If the tens and the units are both zero, no text is added. For any other value, * the name of the one or two-digit number is added as a special case. */ if (tens >= 2) { groupText += NumbersToWords.tens[tens]; if (units != 0) { groupText += " " + smallNumbers[units]; } } else if (tensUnits != 0) { groupText += smallNumbers[tensUnits]; } return(groupText); } /* Negative Rule. * Negative numbers are always preceded by the text 'negative'. */ if (number < 0) { combined = "negative " + combined; } return(combined); }
private void ExecuteOp(OpCode opcode, ExecutionContext context) { if (opcode > OpCode.PUSH16 && opcode != OpCode.RET && context.PushOnly) { State |= VMState.FAULT; return; } if (opcode >= OpCode.PUSHBYTES1 && opcode <= OpCode.PUSHBYTES75) { EvaluationStack.Push(context.OpReader.ReadBytes((byte)opcode)); } else { switch (opcode) { // Push value case OpCode.PUSH0: EvaluationStack.Push(new byte[0]); break; case OpCode.PUSHDATA1: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadByte())); break; case OpCode.PUSHDATA2: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadUInt16())); break; case OpCode.PUSHDATA4: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadInt32())); break; case OpCode.PUSHM1: case OpCode.PUSH1: case OpCode.PUSH2: case OpCode.PUSH3: case OpCode.PUSH4: case OpCode.PUSH5: case OpCode.PUSH6: case OpCode.PUSH7: case OpCode.PUSH8: case OpCode.PUSH9: case OpCode.PUSH10: case OpCode.PUSH11: case OpCode.PUSH12: case OpCode.PUSH13: case OpCode.PUSH14: case OpCode.PUSH15: case OpCode.PUSH16: EvaluationStack.Push((int)opcode - (int)OpCode.PUSH1 + 1); break; // Control case OpCode.NOP: break; case OpCode.JMP: case OpCode.JMPIF: case OpCode.JMPIFNOT: { int offset = context.OpReader.ReadInt16(); offset = context.InstructionPointer + offset - 3; if (offset < 0 || offset > context.Script.Length) { State |= VMState.FAULT; return; } bool fValue = true; if (opcode > OpCode.JMP) { fValue = EvaluationStack.Pop().GetBoolean(); if (opcode == OpCode.JMPIFNOT) { fValue = !fValue; } } if (fValue) { context.InstructionPointer = offset; } } break; case OpCode.CALL: InvocationStack.Push(context.Clone()); context.InstructionPointer += 2; ExecuteOp(OpCode.JMP, CurrentContext); break; case OpCode.RET: InvocationStack.Pop().Dispose(); if (InvocationStack.Count == 0) { State |= VMState.HALT; } break; case OpCode.APPCALL: case OpCode.TAILCALL: { if (table == null) { State |= VMState.FAULT; return; } byte[] script_hash = context.OpReader.ReadBytes(20); if (script_hash.All(p => p == 0)) { script_hash = EvaluationStack.Pop().GetByteArray(); } byte[] script = table.GetScript(script_hash); if (script == null) { State |= VMState.FAULT; return; } if (opcode == OpCode.TAILCALL) { InvocationStack.Pop().Dispose(); } LoadScript(script); } break; case OpCode.SYSCALL: if (!service.Invoke(Encoding.ASCII.GetString(context.OpReader.ReadVarBytes(252)), this)) { State |= VMState.FAULT; } break; // Stack ops case OpCode.DUPFROMALTSTACK: EvaluationStack.Push(AltStack.Peek()); break; case OpCode.TOALTSTACK: AltStack.Push(EvaluationStack.Pop()); break; case OpCode.FROMALTSTACK: EvaluationStack.Push(AltStack.Pop()); break; case OpCode.XDROP: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } EvaluationStack.Remove(n); } break; case OpCode.XSWAP: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } if (n == 0) { break; } StackItem xn = EvaluationStack.Peek(n); EvaluationStack.Set(n, EvaluationStack.Peek()); EvaluationStack.Set(0, xn); } break; case OpCode.XTUCK: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n <= 0) { State |= VMState.FAULT; return; } EvaluationStack.Insert(n, EvaluationStack.Peek()); } break; case OpCode.DEPTH: EvaluationStack.Push(EvaluationStack.Count); break; case OpCode.DROP: EvaluationStack.Pop(); break; case OpCode.DUP: EvaluationStack.Push(EvaluationStack.Peek()); break; case OpCode.NIP: { StackItem x2 = EvaluationStack.Pop(); EvaluationStack.Pop(); EvaluationStack.Push(x2); } break; case OpCode.OVER: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Peek(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); } break; case OpCode.PICK: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } EvaluationStack.Push(EvaluationStack.Peek(n)); } break; case OpCode.ROLL: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } if (n == 0) { break; } EvaluationStack.Push(EvaluationStack.Remove(n)); } break; case OpCode.ROT: { StackItem x3 = EvaluationStack.Pop(); StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x3); EvaluationStack.Push(x1); } break; case OpCode.SWAP: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); } break; case OpCode.TUCK: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); EvaluationStack.Push(x2); } break; case OpCode.CAT: { byte[] x2 = EvaluationStack.Pop().GetByteArray(); byte[] x1 = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x1.Concat(x2).ToArray()); } break; case OpCode.SUBSTR: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } int index = (int)EvaluationStack.Pop().GetBigInteger(); if (index < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Skip(index).Take(count).ToArray()); } break; case OpCode.LEFT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Take(count).ToArray()); } break; case OpCode.RIGHT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); if (x.Length < count) { State |= VMState.FAULT; return; } EvaluationStack.Push(x.Skip(x.Length - count).ToArray()); } break; case OpCode.SIZE: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Length); } break; // Bitwise logic case OpCode.INVERT: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(~x); } break; case OpCode.AND: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 & x2); } break; case OpCode.OR: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 | x2); } break; case OpCode.XOR: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 ^ x2); } break; case OpCode.EQUAL: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x1.Equals(x2)); } break; // Numeric case OpCode.INC: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x + 1); } break; case OpCode.DEC: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x - 1); } break; case OpCode.SIGN: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x.Sign); } break; case OpCode.NEGATE: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(-x); } break; case OpCode.ABS: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Abs(x)); } break; case OpCode.NOT: { bool x = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(!x); } break; case OpCode.NZ: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x != BigInteger.Zero); } break; case OpCode.ADD: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 + x2); } break; case OpCode.SUB: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 - x2); } break; case OpCode.MUL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 * x2); } break; case OpCode.DIV: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 / x2); } break; case OpCode.MOD: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 % x2); } break; case OpCode.SHL: { int n = (int)EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x << n); } break; case OpCode.SHR: { int n = (int)EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x >> n); } break; case OpCode.BOOLAND: { bool x2 = EvaluationStack.Pop().GetBoolean(); bool x1 = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(x1 && x2); } break; case OpCode.BOOLOR: { bool x2 = EvaluationStack.Pop().GetBoolean(); bool x1 = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(x1 || x2); } break; case OpCode.NUMEQUAL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 == x2); } break; case OpCode.NUMNOTEQUAL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 != x2); } break; case OpCode.LT: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 < x2); } break; case OpCode.GT: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 > x2); } break; case OpCode.LTE: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 <= x2); } break; case OpCode.GTE: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 >= x2); } break; case OpCode.MIN: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Min(x1, x2)); } break; case OpCode.MAX: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Max(x1, x2)); } break; case OpCode.WITHIN: { BigInteger b = EvaluationStack.Pop().GetBigInteger(); BigInteger a = EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(a <= x && x < b); } break; // Crypto case OpCode.SHA1: using (SHA1 sha = SHA1.Create()) { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(sha.ComputeHash(x)); } break; case OpCode.SHA256: using (SHA256 sha = SHA256.Create()) { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(sha.ComputeHash(x)); } break; case OpCode.HASH160: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(Crypto.Hash160(x)); } break; case OpCode.HASH256: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(Crypto.Hash256(x)); } break; case OpCode.CHECKSIG: { byte[] pubkey = EvaluationStack.Pop().GetByteArray(); byte[] signature = EvaluationStack.Pop().GetByteArray(); try { EvaluationStack.Push(Crypto.VerifySignature(ScriptContainer.GetMessage(), signature, pubkey)); } catch (ArgumentException) { EvaluationStack.Push(false); } } break; case OpCode.CHECKMULTISIG: { int n; byte[][] pubkeys; StackItem item = EvaluationStack.Pop(); if (item is VMArray array1) { pubkeys = array1.Select(p => p.GetByteArray()).ToArray(); n = pubkeys.Length; if (n == 0) { State |= VMState.FAULT; return; } } else { n = (int)item.GetBigInteger(); if (n < 1 || n > EvaluationStack.Count) { State |= VMState.FAULT; return; } pubkeys = new byte[n][]; for (int i = 0; i < n; i++) { pubkeys[i] = EvaluationStack.Pop().GetByteArray(); } } int m; byte[][] signatures; item = EvaluationStack.Pop(); if (item is VMArray array2) { signatures = array2.Select(p => p.GetByteArray()).ToArray(); m = signatures.Length; if (m == 0 || m > n) { State |= VMState.FAULT; return; } } else { m = (int)item.GetBigInteger(); if (m < 1 || m > n || m > EvaluationStack.Count) { State |= VMState.FAULT; return; } signatures = new byte[m][]; for (int i = 0; i < m; i++) { signatures[i] = EvaluationStack.Pop().GetByteArray(); } } byte[] message = ScriptContainer.GetMessage(); bool fSuccess = true; try { for (int i = 0, j = 0; fSuccess && i < m && j < n;) { if (Crypto.VerifySignature(message, signatures[i], pubkeys[j])) { i++; } j++; if (m - i > n - j) { fSuccess = false; } } } catch (ArgumentException) { fSuccess = false; } EvaluationStack.Push(fSuccess); } break; // Array case OpCode.ARRAYSIZE: { StackItem item = EvaluationStack.Pop(); if (item is ICollection collection) { EvaluationStack.Push(collection.Count); } else { EvaluationStack.Push(item.GetByteArray().Length); } } break; case OpCode.PACK: { int size = (int)EvaluationStack.Pop().GetBigInteger(); if (size < 0 || size > EvaluationStack.Count) { State |= VMState.FAULT; return; } List <StackItem> items = new List <StackItem>(size); for (int i = 0; i < size; i++) { items.Add(EvaluationStack.Pop()); } EvaluationStack.Push(items); } break; case OpCode.UNPACK: { StackItem item = EvaluationStack.Pop(); if (item is VMArray array) { for (int i = array.Count - 1; i >= 0; i--) { EvaluationStack.Push(array[i]); } EvaluationStack.Push(array.Count); } else { State |= VMState.FAULT; return; } } break; case OpCode.PICKITEM: { StackItem key = EvaluationStack.Pop(); if (key is ICollection) { State |= VMState.FAULT; return; } switch (EvaluationStack.Pop()) { case VMArray array: int index = (int)key.GetBigInteger(); if (index < 0 || index >= array.Count) { State |= VMState.FAULT; return; } EvaluationStack.Push(array[index]); break; case Map map: if (map.TryGetValue(key, out StackItem value)) { EvaluationStack.Push(value); } else { State |= VMState.FAULT; return; } break; default: State |= VMState.FAULT; return; } } break; case OpCode.SETITEM: { StackItem value = EvaluationStack.Pop(); if (value is Struct s) { value = s.Clone(); } StackItem key = EvaluationStack.Pop(); if (key is ICollection) { State |= VMState.FAULT; return; } switch (EvaluationStack.Pop()) { case VMArray array: int index = (int)key.GetBigInteger(); if (index < 0 || index >= array.Count) { State |= VMState.FAULT; return; } array[index] = value; break; case Map map: map[key] = value; break; default: State |= VMState.FAULT; return; } } break; case OpCode.NEWARRAY: { int count = (int)EvaluationStack.Pop().GetBigInteger(); List <StackItem> items = new List <StackItem>(count); for (var i = 0; i < count; i++) { items.Add(false); } EvaluationStack.Push(new Types.Array(items)); } break; case OpCode.NEWSTRUCT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); List <StackItem> items = new List <StackItem>(count); for (var i = 0; i < count; i++) { items.Add(false); } EvaluationStack.Push(new VM.Types.Struct(items)); } break; case OpCode.NEWMAP: EvaluationStack.Push(new Map()); break; case OpCode.APPEND: { StackItem newItem = EvaluationStack.Pop(); if (newItem is Types.Struct s) { newItem = s.Clone(); } StackItem arrItem = EvaluationStack.Pop(); if (arrItem is VMArray array) { array.Add(newItem); } else { State |= VMState.FAULT; return; } } break; case OpCode.REVERSE: { StackItem arrItem = EvaluationStack.Pop(); if (arrItem is VMArray array) { array.Reverse(); } else { State |= VMState.FAULT; return; } } break; case OpCode.REMOVE: { StackItem key = EvaluationStack.Pop(); if (key is ICollection) { State |= VMState.FAULT; return; } switch (EvaluationStack.Pop()) { case VMArray array: int index = (int)key.GetBigInteger(); if (index < 0 || index >= array.Count) { State |= VMState.FAULT; return; } array.RemoveAt(index); break; case Map map: map.Remove(key); break; default: State |= VMState.FAULT; return; } } break; case OpCode.HASKEY: { StackItem key = EvaluationStack.Pop(); if (key is ICollection) { State |= VMState.FAULT; return; } switch (EvaluationStack.Pop()) { case VMArray array: int index = (int)key.GetBigInteger(); if (index < 0) { State |= VMState.FAULT; return; } EvaluationStack.Push(index < array.Count); break; case Map map: EvaluationStack.Push(map.ContainsKey(key)); break; default: State |= VMState.FAULT; return; } } break; case OpCode.KEYS: switch (EvaluationStack.Pop()) { case Map map: EvaluationStack.Push(new VMArray(map.Keys)); break; default: State |= VMState.FAULT; return; } break; case OpCode.VALUES: { ICollection <StackItem> values; switch (EvaluationStack.Pop()) { case VMArray array: values = array; break; case Map map: values = map.Values; break; default: State |= VMState.FAULT; return; } List <StackItem> newArray = new List <StackItem>(values.Count); foreach (StackItem item in values) { if (item is Struct s) { newArray.Add(s.Clone()); } else { newArray.Add(item); } } EvaluationStack.Push(new VMArray(newArray)); } break; // Exceptions case OpCode.THROW: State |= VMState.FAULT; return; case OpCode.THROWIFNOT: if (!EvaluationStack.Pop().GetBoolean()) { State |= VMState.FAULT; return; } break; default: State |= VMState.FAULT; return; } } if (!State.HasFlag(VMState.FAULT) && InvocationStack.Count > 0) { if (CurrentContext.BreakPoints.Contains((uint)CurrentContext.InstructionPointer)) { State |= VMState.BREAK; } } }
private string getStringRepresentation() { long shift = this.shift, shift10; BigInteger scale; if (shift >= 0) { int bucketBits = RealMaxBits; BigInteger start = BigInteger.One << bucketBits; long exponent = shift / bucketBits; scale = mostSignificantExponent(start, exponent, out shift10); scale <<= (int)(shift % bucketBits); shiftRightInBase10(ref scale, ref shift10); } else { shift = -shift; int bucketFives = (int)Math.Ceiling(LOG5_2 * RealMaxBits); BigInteger start = BigInteger.Pow(5, bucketFives); long exponent = shift / bucketFives; scale = mostSignificantExponent(start, exponent, out shift10); scale *= BigInteger.Pow(5, (int)(shift % bucketFives)); shiftRightInBase10(ref scale, ref shift10); shift10 -= shift; } BigInteger mantissa = scale * this.mantissa; int digits = (int)Math.Floor(BigInteger.Log10(BigInteger.Abs(mantissa))) - (ToStringDigits + 1); shift10 += digits; mantissa = digits >= 0 ? mantissa / BigInteger.Pow(10, digits) : mantissa *BigInteger.Pow(10, -digits); BigInteger rem, div = BigInteger.DivRem(mantissa, 10, out rem); mantissa = div + (rem <= -5 ? BigInteger.MinusOne : (rem >= 5 ? BigInteger.One : BigInteger.Zero)); //Rounding in base 10. shift10++; while (!mantissa.IsZero) { div = BigInteger.DivRem(mantissa, 10, out rem); if (!rem.IsZero) { break; } mantissa = div; shift10++; } string result = mantissa.ToString(); int dotIndex = (mantissa.Sign < 0 ? 1 : 0) + 1; result = result.Insert(dotIndex, "."); shift10 += result.Length - (dotIndex + 1); if (result[result.Length - 1] == '.') { result = result.Remove(result.Length - 1); } if (shift10 != 0) { result += "e" + (shift10 > 0 ? "+" : "") + shift10.ToString(); } return(result); }
//-------------------------------------------------------------- // Shamir secret sharing //-------------------------------------------------------------- private Dictionary <BigInteger, BigInteger> Shamir(BigInteger secret, BigInteger p, int n, int k, bool is_random_x) { BigInteger[] Koeff = new BigInteger[k - 1]; BigInteger[] rand_x = new BigInteger[n]; Dictionary <BigInteger, BigInteger> total_keys = new Dictionary <BigInteger, BigInteger>(); Random rnd = new Random(); // -------------------------------------- // Creating random koeff a[i]. That will be deleted after creating of shades // -------------------------------------- for (int i = 0; i < k - 1; i++) // gets random a(n), n = 1 ... (k - 1) { Koeff[i] = MathMod(BigInteger.Abs(getRandom((i + 1) * 2)), p); } // -------------------------------------- // creating random X-part of shades ( N times, for N peoples) // -------------------------------------- if (is_random_x) { for (int i = 0; i < n; i++) // gets random x, x count = n { rand_x[i] = MathMod(rnd.Next(1, int.MaxValue - 1), p); // p - BigInt, rand_x[i] - int, can't be rnd.Next of 2 type of value :c } } else { for (int i = 0; i < n; i++) // such non-random! { rand_x[i] = MathMod((i + 1), p); } } // -------------------------------------- // starting Shamir secret sharing // -------------------------------------- BigInteger result = new BigInteger(); BigInteger powered = new BigInteger(); for (int i = 0; i < n; i++) { result = result + secret; for (int j = 1; j < k; j++) // calculate polynomial function for current i, where i = 1 .. n { powered = BigInteger.Pow(rand_x[i], k - j); result += Koeff[j - 1] * powered; } result = MathMod(result, p); if (!total_keys.ContainsKey(rand_x[i])) { total_keys.Add(rand_x[i], result); } else { i--; } result = 0; // set null for next calculates } return(total_keys); // return pair of (x, y) points }
// [DataRow(uint.MaxValue, uint.MaxValue)] // [DataRow(ulong.MaxValue, ulong.MaxValue)] public void UInt128Test(ulong factorMax, ulong modulusMax) { var random = new MersenneTwister(0).Create <ulong>(); for (int i = 0; i < 10000; i++) { var n = random.Next(modulusMax - 1) + 1; var a = random.Next(factorMax) % n; var b = random.Next(factorMax) % n; var c = random.Next(factorMax) % n; var d = random.Next(factorMax) % n; var s = (int)(b % 32); var value = (UInt128)0; Assert.AreEqual((BigInteger)a << s, (UInt128)a << s); Assert.AreEqual((BigInteger)a >> s, (UInt128)a >> s); Assert.AreEqual((BigInteger)a & b, (UInt128)a & b); Assert.AreEqual((BigInteger)a & b, a & (UInt128)b); Assert.AreEqual((BigInteger)a & b, (UInt128)a & (UInt128)b); Assert.AreEqual((BigInteger)a | b, (UInt128)a | b); Assert.AreEqual((BigInteger)a | b, a | (UInt128)b); Assert.AreEqual((BigInteger)a | b, (UInt128)a | (UInt128)b); Assert.AreEqual((BigInteger)a ^ b, (UInt128)a ^ b); Assert.AreEqual((BigInteger)a ^ b, a ^ (UInt128)b); Assert.AreEqual((BigInteger)a ^ b, (UInt128)a ^ (UInt128)b); if (a <= long.MaxValue) { Assert.AreEqual(~(BigInteger)a, (long)~(UInt128)a); } Assert.AreEqual((BigInteger)a + b, (UInt128)a + b); Assert.AreEqual((BigInteger)a + b, a + (UInt128)b); Assert.AreEqual((BigInteger)a + b, (UInt128)a + (UInt128)b); Assert.AreEqual(((BigInteger)a * n + (BigInteger)b * n) % ((BigInteger)1 << 128), (UInt128)a * n + (UInt128)b * n); if (a >= b) { Assert.AreEqual((BigInteger)a - b, (UInt128)a - b); Assert.AreEqual((BigInteger)a - b, a - (UInt128)b); Assert.AreEqual((BigInteger)a - b, (UInt128)a - (UInt128)b); Assert.AreEqual((BigInteger)a * n - (BigInteger)b * n, (UInt128)a * n - (UInt128)b * n); } Assert.AreEqual(+(BigInteger)a, +(Int128)a); value = a; Assert.AreEqual((BigInteger)a + 1, ++value); value = a; Assert.AreEqual((BigInteger)a, value++); value = (UInt128)a * b; Assert.AreEqual((BigInteger)a * b + 1, ++value); value = (UInt128)a * b; Assert.AreEqual((BigInteger)a * b, value++); if (a > 0) { value = a; Assert.AreEqual((BigInteger)a - 1, --value); value = a; Assert.AreEqual((BigInteger)a, value--); } if (a > 0 && b > 0) { value = (UInt128)a * b; Assert.AreEqual((BigInteger)a * b - 1, --value); value = (UInt128)a * b; Assert.AreEqual((BigInteger)a * b, value--); } if (n <= uint.MaxValue) { Assert.AreEqual((BigInteger)a * n, (UInt128)a * (uint)n); Assert.AreEqual((BigInteger)b * n, (UInt128)b * (uint)n); Assert.AreEqual((BigInteger)a * b * n % ((BigInteger)1 << 128), (UInt128)a * b * (uint)n); Assert.AreEqual((BigInteger)n * a, (uint)n * (UInt128)a); Assert.AreEqual((BigInteger)n * b, (uint)n * (UInt128)b); Assert.AreEqual((BigInteger)n * a * b % ((BigInteger)1 << 128), (uint)n * ((UInt128)a * (UInt128)b)); } Assert.AreEqual((BigInteger)a * b, a * (UInt128)b); Assert.AreEqual((BigInteger)a * b, (UInt128)a * b); Assert.AreEqual((BigInteger)a * b, a * (UInt128)b); Assert.AreEqual((BigInteger)a * b, (UInt128)a * (UInt128)b); if (b > 0) { Assert.AreEqual((BigInteger)a % b, (UInt128)a % b); Assert.AreEqual((BigInteger)a % b, a % (UInt128)b); Assert.AreEqual((BigInteger)a % b, (UInt128)a % (UInt128)b); } Assert.AreEqual((BigInteger)a * b % n, (UInt128)a * b % n); Assert.AreEqual((BigInteger)a * b % n, a * (UInt128)b % n); Assert.AreEqual((BigInteger)a * b % n, (UInt128)a * (UInt128)b % (UInt128)n); if (c > 0 && d > 0) { Assert.AreEqual((BigInteger)a * b / ((BigInteger)c * d), (UInt128)a * (UInt128)b / ((UInt128)c * (UInt128)d)); Assert.AreEqual((BigInteger)a * b % ((BigInteger)c * d), (UInt128)a * (UInt128)b % ((UInt128)c * (UInt128)d)); } if (b > 0) { Assert.AreEqual((BigInteger)a / b, (UInt128)a / b); Assert.AreEqual((BigInteger)a / b, a / (UInt128)b); Assert.AreEqual((BigInteger)a / b, (UInt128)a / (UInt128)b); } Assert.AreEqual((BigInteger)a * b / n, (UInt128)a * b / n); Assert.AreEqual((BigInteger)a * b / n, a * (UInt128)b / n); Assert.AreEqual((BigInteger)a * b / n, (UInt128)a * (UInt128)b / (UInt128)n); Assert.AreEqual((BigInteger)a < b, (UInt128)a < b); Assert.AreEqual((BigInteger)a < b, a < (UInt128)b); Assert.AreEqual((BigInteger)a < b, (UInt128)a < (UInt128)b); Assert.AreEqual((BigInteger)a <= b, (UInt128)a <= b); Assert.AreEqual((BigInteger)a <= b, a <= (UInt128)b); Assert.AreEqual((BigInteger)a <= b, (UInt128)a <= (UInt128)b); Assert.AreEqual((BigInteger)a > b, (UInt128)a > b); Assert.AreEqual((BigInteger)a > b, a > (UInt128)b); Assert.AreEqual((BigInteger)a > b, (UInt128)a > (UInt128)b); Assert.AreEqual((BigInteger)a >= b, (UInt128)a >= b); Assert.AreEqual((BigInteger)a >= b, a >= (UInt128)b); Assert.AreEqual((BigInteger)a >= b, (UInt128)a >= (UInt128)b); Assert.AreEqual((BigInteger)a == b, (UInt128)a == b); Assert.AreEqual((BigInteger)a == b, a == (UInt128)b); Assert.AreEqual((BigInteger)a == b, (UInt128)a == (UInt128)b); Assert.AreEqual((BigInteger)a != b, (UInt128)a != b); Assert.AreEqual((BigInteger)a != b, a != (UInt128)b); Assert.AreEqual((BigInteger)a != b, (UInt128)a != (UInt128)b); Assert.AreEqual((BigInteger)a * a, UInt128.Square(a)); Assert.AreEqual(BigInteger.Abs(a), UInt128.Abs(a)); Assert.AreEqual(BigInteger.Abs((BigInteger)a * b), UInt128.Abs((UInt128)a * b)); Assert.AreEqual(BigInteger.Min(a, b), UInt128.Min(a, b)); Assert.AreEqual(BigInteger.Min((BigInteger)a * n, (BigInteger)b * n), UInt128.Min((UInt128)a * n, (UInt128)b * n)); Assert.AreEqual(BigInteger.Max(a, b), UInt128.Max(a, b)); Assert.AreEqual(BigInteger.Max((BigInteger)a * n, (BigInteger)b * n), UInt128.Max((UInt128)a * n, (UInt128)b * n)); for (var j = 0; j < 2; j++) { var m = UInt128.Abs(j == 0 ? (UInt128)a * (UInt128)b : (UInt128)n * (UInt128)n); var floorsqrt = UInt128.FloorSqrt(m); Assert.IsTrue((BigInteger)floorsqrt * floorsqrt <= m && (BigInteger)(floorsqrt + 1) * (floorsqrt + 1) > m); var ceilingsqrt = UInt128.CeilingSqrt(m); Assert.IsTrue((BigInteger)(ceilingsqrt - 1) * (ceilingsqrt - 1) < m && (BigInteger)ceilingsqrt * ceilingsqrt >= m); } for (var j = 0; j < 2; j++) { var m = j == 0 ? (UInt128)a * (UInt128)b : (UInt128)BigInteger.Pow((BigInteger)Math.Floor(Math.Pow((double)((BigInteger)a * b), (double)1 / 3)), 3); var floorcbrt = UInt128.FloorCbrt(m); Assert.IsTrue((BigInteger)floorcbrt * floorcbrt * floorcbrt <= m && (BigInteger)(floorcbrt + 1) * (floorcbrt + 1) * (floorcbrt + 1) > m); var ceilingcbrt = UInt128.CeilingCbrt(m); Assert.IsTrue((BigInteger)(ceilingcbrt - 1) * (ceilingcbrt - 1) * (ceilingcbrt - 1) < m && (BigInteger)ceilingcbrt * ceilingcbrt * ceilingcbrt >= m); } Assert.AreEqual(BigInteger.GreatestCommonDivisor((BigInteger)a, (BigInteger)b), UInt128.GreatestCommonDivisor((UInt128)a, (UInt128)b)); Assert.AreEqual(BigInteger.GreatestCommonDivisor((BigInteger)a * b, (BigInteger)c * d), UInt128.GreatestCommonDivisor((UInt128)a * b, (UInt128)c * d)); Assert.AreEqual(0, 0); } }
public static object BIDivide(BigInteger n, BigInteger d) { if (d.Equals(BigInteger.ZERO)) throw new ArithmeticException("Divide by zero"); //BigInteger gcd = n.gcd(d); BigInteger gcd = n.Gcd(d); if (gcd.Equals(BigInteger.ZERO)) return 0; //n = n.divide(gcd); //d = d.divide(gcd); n = n / gcd; d = d / gcd; if (d.Equals(BigInteger.ONE)) return reduce(n); //return new Ratio((d.signum() < 0 ? n.negate() : n), // (d.signum() < 0 ? d.negate() : d)); return new Ratio((d.Signum < 0 ? -n : n), d.Abs()); }
// Like GetBitCount(Abs(x)), except 0 maps to 0 public static int BitLength(BigInteger x) { if (x.IsZero()) { return 0; } return x.Abs().GetBitCount(); }
private void TestDiv(BigInteger i1, BigInteger i2) { BigInteger q = i1.Divide(i2); BigInteger r = i1.Remainder(i2); BigInteger remainder; BigInteger quotient = i1.DivideAndRemainder(i2, out remainder); Assert.IsTrue(q.Equals(quotient), "Divide and DivideAndRemainder do not agree"); Assert.IsTrue(r.Equals(remainder), "Remainder and DivideAndRemainder do not agree"); Assert.IsTrue(q.Sign != 0 || q.Equals(zero), "signum and equals(zero) do not agree on quotient"); Assert.IsTrue(r.Sign != 0 || r.Equals(zero), "signum and equals(zero) do not agree on remainder"); Assert.IsTrue(q.Sign == 0 || q.Sign == i1.Sign * i2.Sign, "wrong sign on quotient"); Assert.IsTrue(r.Sign == 0 || r.Sign == i1.Sign, "wrong sign on remainder"); Assert.IsTrue(r.Abs().CompareTo(i2.Abs()) < 0, "remainder out of range"); Assert.IsTrue(q.Abs().Add(one).Multiply(i2.Abs()).CompareTo(i1.Abs()) > 0, "quotient too small"); Assert.IsTrue(q.Abs().Multiply(i2.Abs()).CompareTo(i1.Abs()) <= 0, "quotient too large"); BigInteger p = q.Multiply(i2); BigInteger a = p.Add(r); Assert.IsTrue(a.Equals(i1), "(a/b)*b+(a%b) != a"); try { BigInteger mod = i1.Mod(i2); Assert.IsTrue(mod.Sign >= 0, "mod is negative"); Assert.IsTrue(mod.Abs().CompareTo(i2.Abs()) < 0, "mod out of range"); Assert.IsTrue(r.Sign < 0 || r.Equals(mod), "positive remainder == mod"); Assert.IsTrue(r.Sign >= 0 || r.Equals(mod.Subtract(i2)), "negative remainder == mod - divisor"); } catch (ArithmeticException e) { Assert.IsTrue(i2.Sign <= 0, "mod fails on negative divisor only"); } }
public static Rational Abs(Rational x) { return(new Rational(BigInteger.Abs(x.integer), BigInteger.Abs(x.numerator), x.denominator, false)); }
public override string ToString() { if (denominator == 1) { return(integer.ToString()); } if (denominator == 0) { return("Unassigned"); } else { String s; if (numerator < 0) { s = "-"; } else if (integer != 0) { s = "+"; } else { s = ""; } return(String.Format("{0}{1}{2}/{3}", integer != 0 ? integer.ToString() : "", s, BigInteger.Abs(numerator), denominator)); } }
/// <summary> /// Тест Рабина Миллера. Имеет сильно псевдопростые числа /// </summary> /// <param name="source"></param> /// <param name="count"></param> /// <returns></returns> public static PrimalityTestResult MRPT(int source, int count) { if (count >= source) { throw new InvalidOperationException("Число прогонов теста не должно быть меньше тестируемого числа."); } switch (source) { case 0: return(PrimalityTestResult.Composite); case 1: throw new InvalidOperationException("Единица не является ни простым, ни составным числом."); } if (source < 0 || count <= 0) { throw new InvalidOperationException( "Тестируемое число и число его прогонов должны быть положительными числами!"); } //нам необходимо, чтобы число было нечетным, поэтому мы отсеиваем все четные числа. if (source % 2 == 0) { return(PrimalityTestResult.Composite); } int t = source - 1; int s = 0; while (t % 2 == 0) { t /= 2; s++; } //n-1 = (2^s) * t BigInteger[] RestVariants = RD.UniformDistribution(2, source - 1, count); //отрезок [2,n-1] for (int i = 0; i < count; i++) { BigInteger CurrentValue = RestVariants[i]; if (AdvancedEuclidsalgorithm.GCDResult(CurrentValue, source) != 1) { return(PrimalityTestResult.Composite); } //значение символа якоби Comparison.LinearComparison comparison = new Comparison.LinearComparison(CurrentValue, source); if (BigInteger.Abs((comparison = Comparison.MultiplicativeInverse.BinaryPowLinearComparison(comparison, t)) .LeastModulo) == 1) { continue; } while (s != 1) { comparison = Comparison.MultiplicativeInverse.BinaryPowLinearComparison(comparison, 2); if (comparison.LeastModulo == -1) { break; } if (--s == 0) { return(PrimalityTestResult.Composite); } } } return(PrimalityTestResult.Unknown); }
public static string cashAddrToOldAddr(string cashAddr, out bool isP2PKH, out bool mainnet) { cashAddr = cashAddr.ToLower(); if (cashAddr.Length != 54 && cashAddr.Length != 42 && cashAddr.Length != 50) { if (cashAddr.StartsWith("bchreg:")) { throw new CashAddrConversionException("Decoding RegTest addresses is not implemented."); } throw new CashAddrConversionException("Address to be decoded is longer or shorter than expected."); } int afterPrefix; if (cashAddr.StartsWith("bitcoincash:")) { mainnet = true; afterPrefix = 12; } else if (cashAddr.StartsWith("bchtest:")) { mainnet = false; afterPrefix = 8; } else if (cashAddr.StartsWith("bchreg:")) { throw new CashAddrConversionException("Decoding RegTest addresses is not implemented."); } else { if (cashAddr.IndexOf(":") == -1) { mainnet = true; afterPrefix = 0; } else { throw new CashAddrConversionException("Unexpected colon character."); } } int max = afterPrefix + 42; if (max != cashAddr.Length) { throw new CashAddrConversionException("Address to be decoded is longer or shorter than expected."); } byte[] decodedBytes = new byte[42]; for (int i = afterPrefix; i < max; i++) { int value = DICT_CASHADDR[cashAddr[i]]; if (value != -1) { decodedBytes[i - afterPrefix] = (byte)value; } else { throw new CashAddrConversionException("Address contains unexpected character."); } } if (PolyMod(decodedBytes, (ulong)(mainnet ? 1058337025301 : 584719417569)) != 0) { throw new CashAddrConversionException("Address checksum doesn't match. Have you made a mistake while typing it?"); } decodedBytes = convertBitsFiveToEight(decodedBytes); switch (decodedBytes[0]) { case 0x00: isP2PKH = true; break; case 0x08: isP2PKH = false; break; default: throw new CashAddrConversionException("Unexpected address byte."); } if (mainnet && isP2PKH) { decodedBytes[0] = 0x00; } else if (mainnet && !isP2PKH) { decodedBytes[0] = 0x05; } else if (!mainnet && isP2PKH) { decodedBytes[0] = 0x6f; } else { // Warning! Bigger than 0x80. decodedBytes[0] = 0xc4; } SHA256 hasher = SHA256Managed.Create(); byte[] checksum = hasher.ComputeHash(hasher.ComputeHash(decodedBytes, 0, 21)); decodedBytes[21] = checksum[0]; decodedBytes[22] = checksum[1]; decodedBytes[23] = checksum[2]; decodedBytes[24] = checksum[3]; System.Text.StringBuilder ret = new System.Text.StringBuilder(40); for (int numZeros = 0; numZeros < 25 && decodedBytes[numZeros] == 0; numZeros++) { ret.Append("1"); } { var temp = new List <byte>(decodedBytes); // for 0xc4 temp.Insert(0, 0); temp.Reverse(); decodedBytes = temp.ToArray(); } byte[] retArr = new byte[40]; int retIdx = 0; BigInteger baseChanger = BigInteger.Abs(new BigInteger(decodedBytes)); BigInteger baseFiftyEight = new BigInteger(58); BigInteger modulo = new BigInteger(); while (!baseChanger.IsZero) { baseChanger = BigInteger.DivRem(baseChanger, baseFiftyEight, out modulo); retArr[retIdx++] = (byte)modulo; } for (retIdx--; retIdx >= 0; retIdx--) { ret.Append(CHARSET_BASE58[retArr[retIdx]]); } return(ret.ToString()); }
public void Abs_zero_is_zero() { BigInteger z = new BigInteger(0); Expect(z.Abs().IsZero); }
public decimal ToDecimal() { if (Numerator == 0) { return(0m); } var sign = Numerator.Sign; var n = BigInteger.Abs(Numerator) * BigInteger.Pow(10, 28); var d = Denominator; var scale = 28; var limit = (BigInteger.One << 96) - 1; while (scale > 0 && n > d * limit) { --scale; if (n % 10 == 0) { n /= 10; } else { d *= 10; } } if (n > d * limit) { throw new OverflowException(); } // この時点で 0 <= scale <= 127 かつ 0 < n/d <= limit var int_part = n / d; var frac_part_n = n % d; var frac_part_d = d; var frac_part_n2 = frac_part_n * 2; if (frac_part_n2 > frac_part_d) { ++int_part; } else if (frac_part_n2 < frac_part_d) { } else { if (int_part.IsEven) { } else { ++int_part; } } if (int_part > limit) { throw new OverflowException(); } while (int_part % 10 == 0 && scale > 0) { int_part /= 10; --scale; } return(new decimal((int)(uint)(int_part & 0xffffffff), (int)(uint)((int_part >> 32) & 0xffffffff), (int)(uint)((int_part >> 64) & 0xffffffff), sign < 0, (byte)scale)); }
/// <summary> /// Convert a BigInteger to bytes /// </summary> /// /// <param name="X">The BigInteger</param> /// /// <returns>Returns the BigInteger as a byte array</returns> public static byte[] IntToOctets(BigInteger X) { byte[] valBytes = X.Abs().ToByteArray(); // check whether the array includes a sign bit if ((X.BitLength & 7) != 0) return valBytes; // get rid of the sign bit (first byte) byte[] tmp = new byte[X.BitLength >> 3]; Array.Copy(valBytes, 1, tmp, 0, tmp.Length); return tmp; }
public double ToDouble() { var sign = Numerator.Sign; var n = BigInteger.Abs(Numerator) << 1022; var d = Denominator; var scale = -1022; while (n.IsEven && d.IsEven) { n >>= 1; d >>= 1; } if (n < d) { // 非正規化数を返・・・したいのだが c# では非正規化数は表現できないので、0を返す。大丈夫か? return(0d); } while (scale < 1023 && n >= 2 * d) { if (n.IsEven) { n >>= 1; } else { d <<= 1; } ++scale; } if (n >= 2 * d) { return(sign < 0 ? double.NegativeInfinity : double.PositiveInfinity); } var int_part = (n << 52) / d; var frac_part_n = (n << 52) % d; var frac_part_d = d; // 整数部の丸め if (frac_part_n * 2 > frac_part_d) { ++int_part; } else if (frac_part_n * 2 < frac_part_d) { } else { if (int_part.IsEven) { } else { ++int_part; } } if (int_part >= (BigInteger.One << 53)) { int_part >>= 1; ++scale; } if (int_part < (BigInteger.One << 52) || int_part >= (BigInteger.One << 53)) { throw new ApplicationException(string.Format("エラー: Numerator={0}, Denominator={1}", Numerator, Denominator)); } if (scale > 1023 || scale < -1022) { throw new ApplicationException(); } scale -= 52; var r = (double)int_part; if (scale > 0) { r *= (double)(BigInteger.One << scale); } else if (scale < 0) { r /= (double)(BigInteger.One << -scale); } else { } if (sign < 0) { r = -r; } return(r); }
internal static string ToBinary(BigInteger val) { string res = ToBinary(val.Abs(), true, true); if (val.IsNegative()) { res = "-" + res; } return res; }
public MiniRational Abs() { return(new MiniRational(BigInteger.Abs(Numerator), Denominator)); }
// [DataRow(int.MaxValue, int.MaxValue)] // [DataRow(uint.MaxValue, uint.MaxValue)] // [DataRow(long.MaxValue, long.MaxValue)] public void Int128Test(long factorMax, long modulusMax) { var random = new MersenneTwister(0).Create <long>(); for (int i = 0; i < 10000; i++) { var n = random.Next(modulusMax - 1) + 1; var a = random.Next(factorMax) % n - factorMax / 2; var b = random.Next(factorMax) % n - factorMax / 2; var s = (int)(Math.Abs(b) % 32); var value = (Int128)0; Assert.AreEqual((BigInteger)a << s, (Int128)a << s); Assert.AreEqual((BigInteger)a >> s, (Int128)a >> s); Assert.AreEqual((BigInteger)a & b, (Int128)a & b); Assert.AreEqual((BigInteger)a & b, a & (Int128)b); Assert.AreEqual((BigInteger)a & b, (Int128)a & (Int128)b); Assert.AreEqual((BigInteger)a | b, (Int128)a | b); Assert.AreEqual((BigInteger)a | b, a | (Int128)b); Assert.AreEqual((BigInteger)a | b, (Int128)a | (Int128)b); Assert.AreEqual((BigInteger)a ^ b, (Int128)a ^ b); Assert.AreEqual((BigInteger)a ^ b, a ^ (Int128)b); Assert.AreEqual((BigInteger)a ^ b, (Int128)a ^ (Int128)b); if (a <= long.MaxValue) { Assert.AreEqual(~(BigInteger)a, (long)~(Int128)a); } Assert.AreEqual((BigInteger)a + b, (Int128)a + b); Assert.AreEqual((BigInteger)a + b, a + (Int128)b); Assert.AreEqual((BigInteger)a + b, (Int128)a + (Int128)b); Assert.AreEqual(((BigInteger)a * n + (BigInteger)b * n) % ((BigInteger)1 << 128), (Int128)a * n + (Int128)b * n); Assert.AreEqual((BigInteger)a - b, (Int128)a - b); Assert.AreEqual((BigInteger)a - b, a - (Int128)b); Assert.AreEqual((BigInteger)a - b, (Int128)a - (Int128)b); Assert.AreEqual(((BigInteger)a * n - (BigInteger)b * n) % ((BigInteger)1 << 128), (Int128)a * n - (Int128)b * n); Assert.AreEqual(+(BigInteger)a, +(Int128)a); Assert.AreEqual(-(BigInteger)a, -(Int128)a); value = a; Assert.AreEqual((BigInteger)a + 1, ++value); value = a; Assert.AreEqual((BigInteger)a, value++); value = (Int128)a * b; Assert.AreEqual((BigInteger)a * b + 1, ++value); value = (Int128)a * b; Assert.AreEqual((BigInteger)a * b, value++); value = a; Assert.AreEqual((BigInteger)a - 1, --value); value = a; Assert.AreEqual((BigInteger)a, value--); value = (Int128)a * b; Assert.AreEqual((BigInteger)a * b - 1, --value); value = (Int128)a * b; Assert.AreEqual((BigInteger)a * b, value--); Assert.AreEqual((BigInteger)a * b, (Int128)a * b); Assert.AreEqual((BigInteger)a * b, a * (Int128)b); Assert.AreEqual((BigInteger)a * b, (Int128)a * (Int128)b); Assert.AreEqual((BigInteger)a * b % n, (Int128)a * b % n); Assert.AreEqual((BigInteger)a * b % n, a * (Int128)b % n); Assert.AreEqual((BigInteger)a * b % n, (Int128)a * (Int128)b % (Int128)n); Assert.AreEqual((BigInteger)a * b / n, (Int128)a * b / n); Assert.AreEqual((BigInteger)a * b / n, a * (Int128)b / n); Assert.AreEqual((BigInteger)a * b / n, (Int128)a * (Int128)b / (Int128)n); Assert.AreEqual((BigInteger)a < b, (Int128)a < b); Assert.AreEqual((BigInteger)a < b, a < (Int128)b); Assert.AreEqual((BigInteger)a < b, (Int128)a < (Int128)b); Assert.AreEqual((BigInteger)a <= b, (Int128)a <= b); Assert.AreEqual((BigInteger)a <= b, a <= (Int128)b); Assert.AreEqual((BigInteger)a <= b, (Int128)a <= (Int128)b); Assert.AreEqual((BigInteger)a > b, (Int128)a > b); Assert.AreEqual((BigInteger)a > b, a > (Int128)b); Assert.AreEqual((BigInteger)a > b, (Int128)a > (Int128)b); Assert.AreEqual((BigInteger)a >= b, (Int128)a >= b); Assert.AreEqual((BigInteger)a >= b, a >= (Int128)b); Assert.AreEqual((BigInteger)a >= b, (Int128)a >= (Int128)b); Assert.AreEqual((BigInteger)a == b, (Int128)a == b); Assert.AreEqual((BigInteger)a == b, a == (Int128)b); Assert.AreEqual((BigInteger)a == b, (Int128)a == (Int128)b); Assert.AreEqual((BigInteger)a != b, (Int128)a != b); Assert.AreEqual((BigInteger)a != b, a != (Int128)b); Assert.AreEqual((BigInteger)a != b, (Int128)a != (Int128)b); Assert.AreEqual(BigInteger.Abs(a), Int128.Abs(a)); Assert.AreEqual(BigInteger.Abs((BigInteger)a * b), Int128.Abs((Int128)a * b)); Assert.AreEqual(BigInteger.Min(a, b), Int128.Min(a, b)); Assert.AreEqual(BigInteger.Min((BigInteger)a * n, (BigInteger)b * n), Int128.Min((Int128)a * n, (Int128)b * n)); Assert.AreEqual(BigInteger.Max(a, b), Int128.Max(a, b)); Assert.AreEqual(BigInteger.Max((BigInteger)a * n, (BigInteger)b * n), Int128.Max((Int128)a * n, (Int128)b * n)); for (var j = 0; j < 2; j++) { var m = Int128.Abs(j == 0 ? (Int128)a * (Int128)b : (Int128)n * (Int128)n); var floorsqrt = Int128.FloorSqrt(m); Assert.IsTrue((BigInteger)floorsqrt * floorsqrt <= m && (BigInteger)(floorsqrt + 1) * (floorsqrt + 1) > m); var ceilingsqrt = Int128.CeilingSqrt(m); Assert.IsTrue((BigInteger)(ceilingsqrt - 1) * (ceilingsqrt - 1) < m && (BigInteger)ceilingsqrt * ceilingsqrt >= m); } for (var j = 0; j < 2; j++) { var m = j == 0 ? (Int128)a * (Int128)b : (Int128)(Math.Sign(a) * Math.Sign(b) * BigInteger.Pow((BigInteger)Math.Floor(Math.Pow((double)BigInteger.Abs((BigInteger)a * b), (double)1 / 3)), 3)); var floorcbrt = Int128.FloorCbrt(m); Assert.IsTrue(Math.Sign(floorcbrt) == m.Sign && (BigInteger)Math.Abs(floorcbrt) * Math.Abs(floorcbrt) * Math.Abs(floorcbrt) <= BigInteger.Abs(m) && (BigInteger)(Math.Abs(floorcbrt) + 1) * (Math.Abs(floorcbrt) + 1) * (Math.Abs(floorcbrt) + 1) > BigInteger.Abs(m)); var ceilingcbrt = Int128.CeilingCbrt(m); Assert.IsTrue(Math.Sign(ceilingcbrt) == m.Sign && (BigInteger)(Math.Abs(ceilingcbrt) - 1) * (Math.Abs(ceilingcbrt) - 1) * (Math.Abs(ceilingcbrt) - 1) < BigInteger.Abs(m) && (BigInteger)Math.Abs(ceilingcbrt) * Math.Abs(ceilingcbrt) * Math.Abs(ceilingcbrt) >= BigInteger.Abs(m)); } } }
public override string ToString() { String sign = nom / denom >= 0 ? "" : "-"; return(sign + BigInteger.Abs(nom) + "/" + BigInteger.Abs(denom)); }
// Mathematical modulo, that caused by C# modulo(%) is work wrong for mathematical needs. public static BigInteger MathMod(BigInteger a, BigInteger b) { return((BigInteger.Abs(a * b) + a) % b); }
public BigFloat Abs() { numerator = BigInteger.Abs(numerator); return(this); }
public SqlServerFhirStorageTestsFixture() { var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalConnectionString; _databaseName = $"FHIRINTEGRATIONTEST_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}"; string masterConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = "master" }.ToString(); TestConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = _databaseName }.ToString(); var schemaOptions = new SqlServerSchemaOptions { AutomaticUpdatesEnabled = true }; var config = new SqlServerDataStoreConfiguration { ConnectionString = TestConnectionString, Initialize = true, SchemaOptions = schemaOptions }; var schemaInformation = new SchemaInformation(SchemaVersionConstants.Min, SchemaVersionConstants.Max); var scriptProvider = new ScriptProvider <SchemaVersion>(); var baseScriptProvider = new BaseScriptProvider(); var mediator = Substitute.For <IMediator>(); var schemaUpgradeRunner = new SchemaUpgradeRunner(scriptProvider, baseScriptProvider, config, mediator, NullLogger <SchemaUpgradeRunner> .Instance); _schemaInitializer = new SchemaInitializer(config, schemaUpgradeRunner, schemaInformation, NullLogger <SchemaInitializer> .Instance); var searchParameterDefinitionManager = Substitute.For <ISearchParameterDefinitionManager>(); searchParameterDefinitionManager.AllSearchParameters.Returns(new[] { new SearchParameter { Name = SearchParameterNames.Id, Type = SearchParamType.Token, Url = SearchParameterNames.IdUri.ToString() }.ToInfo(), new SearchParameter { Name = SearchParameterNames.LastUpdated, Type = SearchParamType.Date, Url = SearchParameterNames.LastUpdatedUri.ToString() }.ToInfo(), }); var securityConfiguration = new SecurityConfiguration { PrincipalClaims = { "oid" } }; var sqlServerFhirModel = new SqlServerFhirModel(config, _schemaInitializer, searchParameterDefinitionManager, Options.Create(securityConfiguration), NullLogger <SqlServerFhirModel> .Instance); var serviceCollection = new ServiceCollection(); serviceCollection.AddSqlServerTableRowParameterGenerators(); serviceCollection.AddSingleton(sqlServerFhirModel); ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); var upsertResourceTvpGenerator = serviceProvider.GetRequiredService <VLatest.UpsertResourceTvpGenerator <ResourceMetadata> >(); var searchParameterToSearchValueTypeMap = new SearchParameterToSearchValueTypeMap(new SupportedSearchParameterDefinitionManager(searchParameterDefinitionManager)); SqlTransactionHandler = new SqlTransactionHandler(); SqlConnectionWrapperFactory = new SqlConnectionWrapperFactory(config, SqlTransactionHandler, new SqlCommandWrapperFactory()); _fhirDataStore = new SqlServerFhirDataStore(config, sqlServerFhirModel, searchParameterToSearchValueTypeMap, upsertResourceTvpGenerator, Options.Create(new CoreFeatureConfiguration()), SqlConnectionWrapperFactory, NullLogger <SqlServerFhirDataStore> .Instance, schemaInformation); _fhirOperationDataStore = new SqlServerFhirOperationDataStore(SqlConnectionWrapperFactory, NullLogger <SqlServerFhirOperationDataStore> .Instance); _testHelper = new SqlServerFhirStorageTestHelper(TestConnectionString, initialConnectionString, masterConnectionString, sqlServerFhirModel); }
/// <summary> /// Gets the absolute value of a <see cref="Fraction"/> object. /// </summary> /// <param name="fraction">The fraction.</param> /// <returns>The absolute value.</returns> public static Fraction Abs(Fraction fraction) { return(new Fraction(BigInteger.Abs(fraction.Numerator), BigInteger.Abs(fraction.Denominator), fraction.State)); }
PluginResult NewCallOpNode(ref ExpressionNode Node) { var OpNode = Node as OpExpressionNode; var Op = OpNode.Operator; var Ch = OpNode.Children; var Ok = true; for (var i = 1; i < Ch.Length; i++) { if (!(Ch[i] is ConstExpressionNode)) { Ok = false; break; } } // ------------------------------------------------------------------------------------ var IdCh0 = Ch[0] as IdExpressionNode; if (IdCh0 != null && IdCh0.Identifier is Function && Ok) { var Func = IdCh0.Identifier as Function; var FuncType = Func.TypeOfSelf.RealId as TypeOfFunction; var RetType = FuncType.RetType; var Name = Func.AssemblyNameWithoutDecorations; var RetValue = (ConstValue)null; if (Name != null && Name.StartsWith("_System_Math_")) { if (Ch.Length == 2) { var Param0Node = Ch[1] as ConstExpressionNode; var Param0RealId = Param0Node.Type.RealId; var Param0Value = Param0Node.Value; if (!(Param0RealId is NumberType)) { return(PluginResult.Succeeded); } if (Name == "_System_Math_Abs") { RetValue = Param0Value; if (Param0RealId is FloatType) { var FractionValue = Param0Value as DoubleValue; FractionValue.Value = Math.Abs(FractionValue.Value); } else { var IntegerValue = Param0Value as IntegerValue; IntegerValue.Value = BigInteger.Abs(IntegerValue.Value); } } else if (Name == "_System_Math_Sqrt") { if (Param0RealId is FloatType) { RetValue = Param0Value; var FractionValue = Param0Value as DoubleValue; FractionValue.Value = Math.Sqrt(FractionValue.Value); } else { var IntegerValue = Param0Value as IntegerValue; RetValue = new DoubleValue(Math.Sqrt((double)IntegerValue.Value)); } } else if (Name == "_System_Math_Sign") { RetValue = Param0Value; if (Param0RealId is FloatType) { var FractionValue = Param0Value as DoubleValue; FractionValue.Value = Math.Sign(FractionValue.Value); } else { var IntegerValue = Param0Value as IntegerValue; if (IntegerValue.Value < 0) { IntegerValue.Value = -1; } else if (IntegerValue.Value > 0) { IntegerValue.Value = 1; } else { IntegerValue.Value = 0; } } } else if (Name == "_System_Math_Log") { RetValue = new DoubleValue(Math.Log(Param0Value.Double)); } else if (Name == "_System_Math_Log2") { RetValue = new DoubleValue(Math.Log(Param0Value.Double, 2)); } else if (Name == "_System_Math_Log10") { Param0Value = new DoubleValue(Math.Log10(Param0Value.Double)); } else if (Name == "_System_Math_Exp") { RetValue = new DoubleValue(Math.Exp(Param0Value.Double)); } else if (Name == "_System_Math_Pow2") { Param0Value = new DoubleValue(Math.Pow(2, Param0Value.Double)); } else if (Name == "_System_Math_Sin") { RetValue = new DoubleValue(Math.Sin(Param0Value.Double)); } else if (Name == "_System_Math_Cos") { RetValue = new DoubleValue(Math.Cos(Param0Value.Double)); } else if (Name == "_System_Math_Tan") { RetValue = new DoubleValue(Math.Tan(Param0Value.Double)); } else if (Name == "_System_Math_Asin") { RetValue = new DoubleValue(Math.Asin(Param0Value.Double)); } else if (Name == "_System_Math_Acos") { RetValue = new DoubleValue(Math.Acos(Param0Value.Double)); } else if (Name == "_System_Math_Atan") { RetValue = new DoubleValue(Math.Atan(Param0Value.Double)); } else if (Name == "_System_Math_Sinh") { RetValue = new DoubleValue(Math.Sinh(Param0Value.Double)); } else if (Name == "_System_Math_Cosh") { RetValue = new DoubleValue(Math.Cosh(Param0Value.Double)); } else if (Name == "_System_Math_Tanh") { RetValue = new DoubleValue(Math.Tanh(Param0Value.Double)); } else if (Name == "_System_Math_Asinh") { var X = Param0Value.Double; RetValue = new DoubleValue(Math.Log(X + Math.Sqrt(X * X + 1))); } else if (Name == "_System_Math_Acosh") { var X = Param0Value.Double; RetValue = new DoubleValue(Math.Log(X + Math.Sqrt(X * X - 1))); } else if (Name == "_System_Math_Atanh") { var X = Param0Value.Double; RetValue = new DoubleValue(0.5d * Math.Log((1 + X) / (1 - X))); } } else if (Ch.Length == 3) { var Param0Node = Ch[1] as ConstExpressionNode; var Param0RealId = Param0Node.Type.RealId; var Param0Value = Param0Node.Value; var Param1Node = Ch[2] as ConstExpressionNode; var Param1RealId = Param1Node.Type.RealId; var Param1Value = Param1Node.Value; if (!(Param0RealId is NumberType && Param1RealId is NumberType)) { return(PluginResult.Succeeded); } if (Name == "_System_Math_Pow") { var X = Param0Value.Double; var Y = Param1Value.Double; RetValue = new DoubleValue(Math.Pow(X, Y)); } else if (Name == "_System_Math_Log") { var X = Param0Value.Double; var Y = Param1Value.Double; RetValue = new DoubleValue(Math.Log(X, Y)); } else if (Name == "_System_Math_Atan2") { var X = Param0Value.Double; var Y = Param1Value.Double; RetValue = new DoubleValue(Math.Atan2(X, Y)); } } } if (RetValue != null) { Node = RetValue.ToExpression(Parent, RetType, Node.Code); return(Node == null ? PluginResult.Failed : PluginResult.Ready); } } return(PluginResult.Succeeded); }
public static BigInteger Abs(this BigInteger self) { return(BigInteger.Abs(self)); }
internal static ECPoint ImplShamirsTrickWNaf(ECPoint P, BigInteger k, ECPointMap pointMapQ, BigInteger l) { bool negK = k.SignValue < 0, negL = l.SignValue < 0; k = k.Abs(); l = l.Abs(); int width = System.Math.Max(2, System.Math.Min(16, WNafUtilities.GetWindowSize(System.Math.Max(k.BitLength, l.BitLength)))); ECPoint Q = WNafUtilities.MapPointWithPrecomp(P, width, true, pointMapQ); WNafPreCompInfo infoP = WNafUtilities.GetWNafPreCompInfo(P); WNafPreCompInfo infoQ = WNafUtilities.GetWNafPreCompInfo(Q); ECPoint[] preCompP = negK ? infoP.PreCompNeg : infoP.PreComp; ECPoint[] preCompQ = negL ? infoQ.PreCompNeg : infoQ.PreComp; ECPoint[] preCompNegP = negK ? infoP.PreComp : infoP.PreCompNeg; ECPoint[] preCompNegQ = negL ? infoQ.PreComp : infoQ.PreCompNeg; byte[] wnafP = WNafUtilities.GenerateWindowNaf(width, k); byte[] wnafQ = WNafUtilities.GenerateWindowNaf(width, l); return ImplShamirsTrickWNaf(preCompP, preCompNegP, wnafP, preCompQ, preCompNegQ, wnafQ); }
public static object Abs(BigInteger /*!*/ self) { return(Protocols.Normalize(self.Abs())); }
/// <summary> /// Generates a random number. /// </summary> /// <returns>A new random number.</returns> public static BigInteger GenerateRandomInt() { s_RndGen.GetBytes(s_Buff); return(BigInteger.Abs(new BigInteger(s_Buff))); }
// PROTOCOL: // ClntToSvr: "Client", Ra // SvrToClnt: Rb, E("Svr", Ra, g^b modp, Kab) // ClntToSvr: E("Client", Rb, g^a modp, Kab) public byte[] AsClient() { var r = new Random(); // ClntToSvr: "Client", Ra var RaBytes = RandomBytes(Variables.RaRbLength, r); CConsole.WriteLine("Challenging with Ra: " + RaBytes.ByteArrToStr(), ConsoleColor.Green); Console.WriteLine(""); var m = new List <byte>(); m.Add((byte)ModeByte.Client); m.AddRange(RaBytes); CConsole.Write("Sending Message: 'Client',Ra:", ConsoleColor.Green); SendMessageSync(m); Console.WriteLine(""); // wait for: SvrToClnt: Rb, E("Svr", Ra, g^b modp, Kab) CConsole.Write("Waiting for Message: Rb, E('Server', Ra, g^b mod p ):", ConsoleColor.Green); var rcvd = WaitMessageSync().ToList(); Console.WriteLine(""); //given above uint, expect first {Variables.RaRbLength} bytes as RB, rest as E("Svr",Ra, g^b modp, Kab) var Rb = rcvd.Take(Variables.RaRbLength).ToArray(); CConsole.WriteLine("I am challenged with Rb: " + Rb.ByteArrToStr(), ConsoleColor.Green); Console.WriteLine(""); // decrypt E("Svr", Ra, g^b modp, Kab) var dec = cipher.Decrypt(rcvd.Skip(Variables.RaRbLength)); // Server authentication if (dec.First() != (byte)ModeByte.Server) { throw new UnauthorizedAccessException("Received message did not come from server, Or the password do not match."); } // if Ra != received and decrypted ra if (!ByteArrMatches(dec.Skip(1).Take(Variables.RaRbLength), RaBytes)) { throw new UnauthorizedAccessException("Password mismatch"); } CConsole.WriteLine("Received Ra challenge response and passed: " + RaBytes.ByteArrToStr(), ConsoleColor.Green); Console.WriteLine(""); // get g^b mod p value var gbmodp = dec.Skip(1 + Variables.RaRbLength).ToArray(); BigInteger DHb_val = new BigInteger(gbmodp); CConsole.WriteLine("Received D-H g^b mod p value: " + DHb_val, ConsoleColor.Green); Console.WriteLine(""); DiffieHellman DH = new DiffieHellman(); // generate g^a mod p var a = BigInteger.Abs(new BigInteger(RandomBytes(Variables.DHCoefficientLength, r))); var DHa_val = DH.hardComputeSharedDH(a); CConsole.WriteLine("My D-H coffefficient chosen: " + a, ConsoleColor.Green); Console.WriteLine(""); CConsole.WriteLine("Sending my D-H g^a mod p value : " + DHa_val, ConsoleColor.Green); Console.WriteLine(""); // ClntToSvr: E("Client", Rb, g^a modp, Kab) m.Clear(); m.Add((byte)ModeByte.Client); m.AddRange(Rb); m.AddRange(DHa_val.ToByteArray()); m = cipher.Encrypt(m).ToList <byte>(); CConsole.Write("Sending Message: E('Client', Rb, g^a mod p) :", ConsoleColor.Green); SendMessageSync(m); Console.WriteLine(""); // calculate DH value BigInteger DH_final = DH.hardComputeFinalDH(DHb_val, a); CConsole.WriteLine("The g^ab mod p value is:" + DH_final, ConsoleColor.Green); Console.WriteLine(""); CConsole.WriteLine("Key is: " + DH_final.ToByteArray().ByteArrToStr(), ConsoleColor.Magenta); return(DH_final.ToByteArray()); }
/** @see BigInteger#ToString(int) */ public static string BigInteger2String(BigInteger val, int radix) { int sign = val.Sign; int numberLength = val.numberLength; int[] digits = val.Digits; if (sign == 0) { return "0"; //$NON-NLS-1$ } if (numberLength == 1) { int highDigit = digits[numberLength - 1]; long v = highDigit & 0xFFFFFFFFL; if (sign < 0) { // Long.ToString has different semantic from C# for negative numbers return "-" + Convert.ToString(v, radix); } return Convert.ToString(v, radix); } if ((radix == 10) || (radix < CharHelper.MIN_RADIX) || (radix > CharHelper.MAX_RADIX)) { return val.ToString(); } double bitsForRadixDigit; bitsForRadixDigit = System.Math.Log(radix) / System.Math.Log(2); int resLengthInChars = (int)(val.Abs().BitLength / bitsForRadixDigit + ((sign < 0) ? 1 : 0)) + 1; char[] result = new char[resLengthInChars]; int currentChar = resLengthInChars; int resDigit; if (radix != 16) { int[] temp = new int[numberLength]; Array.Copy(digits, 0, temp, 0, numberLength); int tempLen = numberLength; int charsPerInt = digitFitInInt[radix]; int i; // get the maximal power of radix that fits in int int bigRadix = bigRadices[radix - 2]; while (true) { // divide the array of digits by bigRadix and convert remainders // to CharHelpers collecting them in the char array resDigit = Division.DivideArrayByInt(temp, temp, tempLen, bigRadix); int previous = currentChar; do { result[--currentChar] = CharHelper.forDigit( resDigit % radix, radix); } while (((resDigit /= radix) != 0) && (currentChar != 0)); int delta = charsPerInt - previous + currentChar; for (i = 0; i < delta && currentChar > 0; i++) { result[--currentChar] = '0'; } for (i = tempLen - 1; (i > 0) && (temp[i] == 0); i--) { ; } tempLen = i + 1; if ((tempLen == 1) && (temp[0] == 0)) { // the quotient is 0 break; } } } else { // radix == 16 for (int i = 0; i < numberLength; i++) { for (int j = 0; (j < 8) && (currentChar > 0); j++) { resDigit = digits[i] >> (j << 2) & 0xf; result[--currentChar] = CharHelper.forDigit(resDigit, 16); } } } while (result[currentChar] == '0') { currentChar++; } if (sign == -1) { result[--currentChar] = '-'; } return new String(result, currentChar, resLengthInChars - currentChar); }
/* PROTOCOL IS AS FOLLOWS: */ // ClntToSvr: "Client", Ra // SvrToClnt: Rb, E("Svr", Ra, g^b modp, Kab) // ClntToSvr: E("Client", Rb, g^a modp, Kab) public byte[] AsServer() { //wait for: ClntToSvr: "Client", Ra CConsole.Write("Waiting for Message: 'Client',Ra :", ConsoleColor.Green); var rcvd = WaitMessageSync(); Console.WriteLine(""); // check "client" authentication message if (rcvd.First() != (byte)ModeByte.Client) { throw new UnauthorizedAccessException("received message is not sent from client"); } // get Ra var RaBytes = rcvd.Skip(1); CConsole.WriteLine("I am challenged with Ra: " + RaBytes.ByteArrToStr(), ConsoleColor.Green); Console.WriteLine(""); // make Rb var r = new Random(); var RbBytes = RandomBytes(Variables.RaRbLength, r); CConsole.WriteLine("Challenging with Rb: " + RbBytes.ByteArrToStr(), ConsoleColor.Green); Console.WriteLine(""); DiffieHellman DH = new DiffieHellman(); // generate g^b mod p var b = BigInteger.Abs(new BigInteger(RandomBytes(Variables.DHCoefficientLength, r))); var DHb_val = DH.hardComputeSharedDH(b); CConsole.WriteLine("My D-H coefficient chosen: " + b, ConsoleColor.Green); Console.WriteLine(""); CConsole.WriteLine("Sending D-H g^b mod p value: " + DHb_val, ConsoleColor.Green); Console.WriteLine(""); var enc = new List <byte>(); //corresponds to E("Svr", Ra, g^b modp, Kab) enc.Add((byte)ModeByte.Server); enc.AddRange(RaBytes); enc.AddRange(DHb_val.ToByteArray()); enc = cipher.Encrypt(enc).ToList <byte>(); var m = new List <byte>(); // m is (Rb, Enc) m.AddRange(RbBytes); m.AddRange(enc); // SvrToClnt: Rb, E("Svr", Ra, g^b modp, Kab) CConsole.WriteLine("Sending Rb, E('Sever',Ra, g^b mod p) " + DHb_val, ConsoleColor.Green); SendMessageSync(m); Console.WriteLine(""); // wait for: ClntToSvr: E("Client", Rb, g^a modp, Kab) CConsole.Write("Waiting for Message: E('Client', Rb, g^a mod p ):", ConsoleColor.Green); rcvd = cipher.Decrypt(WaitMessageSync()); // wait for "Client" authentication msg if (rcvd.First() != (byte)ModeByte.Client) { throw new UnauthorizedAccessException("received message did not come from client, Or the passwords do not match."); } // check challenge: if Rb != received and decrypted rb if (!ByteArrMatches(rcvd.Skip(1).Take(Variables.RaRbLength), (RbBytes))) { throw new UnauthorizedAccessException("Password mismatch"); } // get g^a mod p value var gamodp = rcvd.Skip(1 + Variables.RaRbLength).ToArray(); var DHa_val = new BigInteger(gamodp); CConsole.WriteLine("Received D-H g^b mod p value: " + DHa_val, ConsoleColor.Green); Console.WriteLine(""); // calculate DH value BigInteger DH_final = DH.hardComputeFinalDH(DHa_val, b); CConsole.WriteLine("The g^ab mod p value is:" + DH_final, ConsoleColor.Green); Console.WriteLine(""); CConsole.WriteLine("Key is: " + DH_final.ToByteArray().ByteArrToStr(), ConsoleColor.Magenta); return(DH_final.ToByteArray()); }
public void Abs_pos_is_pos() { uint[] data = new uint[] { 0x1, 0x2, 0x3 }; BigInteger i = new BigInteger(1, data); Expect(SameValue(i.Abs(), 1, data)); }
public static object __abs__(BigInteger x) { return(x.Abs()); }
void PrintInteger(StringBuilder sb, BigInteger val) { StringBuilder sb1 = new StringBuilder(); bool neg = val.IsNegative; BigInteger v = val.Abs(); PrintLeadingSign(sb1,neg); if ( _conversion == ConversionAux.DecimalInteger ) PrintMagnitude(sb1,neg,v.ToString()); else { string s = v.ToString( _conversion == ConversionAux.OctalInteger ? 8u : 16u ); PrintIntOctHex(sb1,s,neg,true); } PrintTrailingSign(sb1,neg); PrintWithJustification(sb,sb1.ToString()); }
public SqlServerFhirStorageTestsFixture() { var initialConnectionString = Environment.GetEnvironmentVariable("SqlServer:ConnectionString") ?? LocalConnectionString; _databaseName = $"FHIRINTEGRATIONTEST_{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}_{BigInteger.Abs(new BigInteger(Guid.NewGuid().ToByteArray()))}"; _masterConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = "master" }.ToString(); TestConnectionString = new SqlConnectionStringBuilder(initialConnectionString) { InitialCatalog = _databaseName }.ToString(); var config = new SqlServerDataStoreConfiguration { ConnectionString = TestConnectionString, Initialize = true }; var schemaUpgradeRunner = new SchemaUpgradeRunner(config, NullLogger <SchemaUpgradeRunner> .Instance); var schemaInformation = new SchemaInformation(); _schemaInitializer = new SchemaInitializer(config, schemaUpgradeRunner, schemaInformation, NullLogger <SchemaInitializer> .Instance); var searchParameterDefinitionManager = Substitute.For <ISearchParameterDefinitionManager>(); searchParameterDefinitionManager.AllSearchParameters.Returns(new[] { new SearchParameter { Name = SearchParameterNames.Id, Url = SearchParameterNames.IdUri.ToString() }.ToInfo(), new SearchParameter { Name = SearchParameterNames.LastUpdated, Url = SearchParameterNames.LastUpdatedUri.ToString() }.ToInfo(), }); var securityConfiguration = new SecurityConfiguration { PrincipalClaims = { "oid" } }; var sqlServerFhirModel = new SqlServerFhirModel(config, schemaInformation, searchParameterDefinitionManager, Options.Create(securityConfiguration), NullLogger <SqlServerFhirModel> .Instance); var serviceCollection = new ServiceCollection(); serviceCollection.AddSqlServerTableRowParameterGenerators(); serviceCollection.AddSingleton(sqlServerFhirModel); ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider(); var upsertResourceTvpGenerator = serviceProvider.GetRequiredService <V1.UpsertResourceTvpGenerator <ResourceMetadata> >(); var searchParameterToSearchValueTypeMap = new SearchParameterToSearchValueTypeMap(searchParameterDefinitionManager); _fhirDataStore = new SqlServerFhirDataStore(config, sqlServerFhirModel, searchParameterToSearchValueTypeMap, upsertResourceTvpGenerator, NullLogger <SqlServerFhirDataStore> .Instance); _testHelper = new SqlServerFhirStorageTestHelper(TestConnectionString); }
protected virtual BigInteger ModReduce(BigInteger x) { if (r == null) { x = x.Mod(q); } else { bool negative = x.SignValue < 0; if (negative) { x = x.Abs(); } int qLen = q.BitLength; if (r.SignValue > 0) { BigInteger qMod = BigInteger.One.ShiftLeft(qLen); bool rIsOne = r.Equals(BigInteger.One); while (x.BitLength > (qLen + 1)) { BigInteger u = x.ShiftRight(qLen); BigInteger v = x.Remainder(qMod); if (!rIsOne) { u = u.Multiply(r); } x = u.Add(v); } } else { int d = ((qLen - 1) & 31) + 1; BigInteger mu = r.Negate(); BigInteger u = mu.Multiply(x.ShiftRight(qLen - d)); BigInteger quot = u.ShiftRight(qLen + d); BigInteger v = quot.Multiply(q); BigInteger bk1 = BigInteger.One.ShiftLeft(qLen + d); v = v.Remainder(bk1); x = x.Remainder(bk1); x = x.Subtract(v); if (x.SignValue < 0) { x = x.Add(bk1); } } while (x.CompareTo(q) >= 0) { x = x.Subtract(q); } if (negative && x.SignValue != 0) { x = q.Subtract(x); } } return x; }
public static void AreEqual(BigInteger expected, BigInteger actual, double tolerance = 0) { Assert.AreEqual(0, (double)BigInteger.Abs(actual - expected), tolerance); }
/// <summary> /// Computes the value of the Jacobi symbol (A|B). /// </summary> /// /// <param name="A">The integer value</param> /// <param name="B">The integer value</param> /// /// <returns>Returns value of the jacobi symbol (A|B)</returns> public static int Jacobi(BigInteger A, BigInteger B) { BigInteger a, b, v; long k = 1; // test trivial cases if (B.Equals(ZERO)) { a = A.Abs(); return a.Equals(ONE) ? 1 : 0; } if (!A.TestBit(0) && !B.TestBit(0)) return 0; a = A; b = B; if (b.Signum() == -1) { // b < 0 b = b.Negate(); if (a.Signum() == -1) k = -1; } v = ZERO; while (!b.TestBit(0)) { v = v.Add(ONE); b = b.Divide(TWO); } if (v.TestBit(0)) k = k * _jacobiTable[a.ToInt32() & 7]; if (a.Signum() < 0) { if (b.TestBit(1)) k = -k; a = a.Negate(); } // main loop while (a.Signum() != 0) { v = ZERO; while (!a.TestBit(0)) { // a is even v = v.Add(ONE); a = a.Divide(TWO); } if (v.TestBit(0)) k = k * _jacobiTable[b.ToInt32() & 7]; if (a.CompareTo(b) < 0) { // swap and correct intermediate result BigInteger x = a; a = b; b = x; if (a.TestBit(1) && b.TestBit(1)) k = -k; } a = a.Subtract(b); } return b.Equals(ONE) ? (int)k : 0; }
// -------- SECTION: public static methods -----------------* #region Public Static Methods public static BigRational Abs(BigRational r) { return (r.m_numerator.Sign < 0 ? new BigRational(BigInteger.Abs(r.m_numerator), r.Denominator) : r); }
public static object BIDivide(BigInteger n, BigInteger d) { if (d.Equals(BigInteger.ZERO)) throw new ArithmeticException("Divide by zero"); BigInteger gcd = n.Gcd(d); if (gcd.Equals(BigInteger.ZERO)) return BigInt.ZERO; n = n / gcd; d = d / gcd; if (d.Equals(BigInteger.ONE)) return BigInt.fromBigInteger(n); else if (d.Equals(BigInteger.NEGATIVE_ONE)) return BigInt.fromBigInteger(n.Negate()); return new Ratio((d.Signum < 0 ? -n : n), d.Abs()); }
/// <summary> /// Converts the number to a string of the specified base. /// </summary> public static string ToString(this BigInteger value, int numberBase, bool signed, int minWidth) { // Validate if (numberBase < 2 || numberBase > 16) { throw new ArgumentOutOfRangeException(nameof(numberBase)); } if (minWidth < 0) { throw new ArgumentOutOfRangeException(nameof(minWidth)); } var negative = value < 0; if (negative && !signed) { throw new ArgumentOutOfRangeException(nameof(value)); } // Decide how to handle sign according to base var bitBased = true; var bitsPerDigit = 1; if (numberBase > 2) { var baseRoot = Math.Sqrt(numberBase); bitsPerDigit = (int)Math.Floor(baseRoot); bitBased = !(baseRoot - bitsPerDigit > 0); } // Detect sign and prepare negative conversion var result = new StringBuilder(minWidth); var negate = false; if (negative) { // Make value positive for conversion value = BigInteger.Abs(value); // Make negative if (bitBased) { // Setup two's complement for bit based conversion value--; negate = true; } else { // Just prepend negative sign to other number bases result.Append('-'); } } // Divide into string of digits... var firstDigit = result.Length; var quotient = value; do { // Divide quotient by base var dividend = BigInteger.Abs(quotient / numberBase); var remainder = quotient - numberBase * dividend; quotient = dividend; // Use remainder as digit from right to left var digit = (int)(negate ? numberBase - 1 - remainder : remainder); result.Insert(firstDigit, new[] { NumberDigits[digit] }); // Add padding at last position of bit based values when necessary if (quotient < 1 && signed && bitBased) { if (negative) { // Ensure negative binary values have at least 2 bits (one for sign) if (bitsPerDigit == 1 && result.Length == 1 && minWidth < 2) { minWidth = 2; } } else { // Pad with zero when non-negative but MSB set in value var negativeBitValue = 1 << (bitsPerDigit - 1); var negativeBitSet = (negativeBitValue & digit) != 0; if (negativeBitSet) { var positiveWidth = result.Length - firstDigit + 1; if (minWidth < positiveWidth) { minWidth = positiveWidth; } } } } } while (quotient > 0); // Pad string to desired width while (result.Length - firstDigit < minWidth) { result.Insert(firstDigit, new[] { negate?NumberDigits[numberBase - 1] : NumberDigits[0] }); } // Return result return(result.ToString()); }
public static object __abs__(BigInteger x) { return x.Abs(); }
/// <summary> /// The classic GCD algorithm of Euclid /// </summary> /// <param name="smaller"></param> /// <param name="larger"></param> /// <returns></returns> internal BigInteger Gcd(BigInteger smaller, BigInteger larger) { BigInteger rest; smaller = smaller.Abs(); larger = larger.Abs(); if (smaller == 0) return larger; else { if (larger == 0) return smaller; } // the GCD algorithm requires second >= first if(smaller > larger) { rest = larger; larger = smaller; smaller = rest; } while((rest = larger%smaller) != 0) { larger = smaller; smaller = rest; } return smaller; }