コード例 #1
0
ファイル: BigDec.cs プロジェクト: emptylambda/RobustIVL
        public static BigDec FromString(string v)
        {
            if (v == null)
            {
                throw new FormatException();
            }

            BIM integral = BIM.Zero;
            BIM fraction = BIM.Zero;
            int exponent = 0;

            int len = v.Length;

            int i = v.IndexOf('e');

            if (i >= 0)
            {
                if (i + 1 == v.Length)
                {
                    throw new FormatException();
                }
                exponent = Int32.Parse(v.Substring(i + 1, len - i - 1));
                len      = i;
            }

            int fractionLen = 0;

            i = v.IndexOf('.');
            if (i >= 0)
            {
                if (i + 1 == v.Length)
                {
                    throw new FormatException();
                }
                fractionLen = len - i - 1;
                fraction    = BIM.Parse(v.Substring(i + 1, fractionLen));
                len         = i;
            }

            integral = BIM.Parse(v.Substring(0, len));

            if (!fraction.IsZero)
            {
                while (fractionLen > 0)
                {
                    integral    = integral * ten;
                    exponent    = exponent - 1;
                    fractionLen = fractionLen - 1;
                }
            }

            if (integral.Sign == -1)
            {
                return(new BigDec(integral - fraction, exponent));
            }
            else
            {
                return(new BigDec(integral + fraction, exponent));
            }
        }
コード例 #2
0
        public Dictionary <string, object> CreatePrivateKey()
        {
            var rand = new Random(DateTimeOffset.UtcNow.Millisecond);
            var pp   = RandomPrime(1024, rand);
            var qq   = RandomPrime(1024, rand);

            var p = BigInt.Parse(pp.ToString());
            var q = BigInt.Parse(qq.ToString());
            // Console.WriteLine($"p = {p}");
            // Console.WriteLine($"q = {q}");
            var n   = q * p;
            var phi = (p - 1) * (q - 1);
            var e   = RandomPrime(8, rand);

            Gcd(e, phi, out var x, out var y);

            var d = x > 0 ? x : x + phi;

            // Console.WriteLine($"phi = {phi}");
            // Console.WriteLine($"x = {x}");
            // Console.WriteLine($"y = {y}");
            // Console.WriteLine($"d = {d}");


            var result = new Dictionary <string, object>();

            result.Add("p", p.ToString());
            result.Add("q", q.ToString());
            result.Add("n", n.ToString());
            result.Add("phi", phi.ToString());
            result.Add("e", e.ToString());
            result.Add("d", d.ToString());
            return(result);
        }
コード例 #3
0
 public void LcmSupportsLargeInput()
 {
     Assert.AreEqual((BigInteger)Int32.MaxValue, Euclid.LeastCommonMultiple((BigInteger)Int32.MaxValue, Int32.MaxValue), "Lcm(Int32Max,Int32Max)");
     Assert.AreEqual((BigInteger)Int64.MaxValue, Euclid.LeastCommonMultiple((BigInteger)Int64.MaxValue, Int64.MaxValue), "Lcm(Int64Max,Int64Max)");
     Assert.AreEqual((BigInteger)Int64.MaxValue, Euclid.LeastCommonMultiple((BigInteger)(-Int64.MaxValue), -Int64.MaxValue), "Lcm(-Int64Max,-Int64Max)");
     Assert.AreEqual((BigInteger)Int64.MaxValue, Euclid.LeastCommonMultiple((BigInteger)(-Int64.MaxValue), Int64.MaxValue), "Lcm(-Int64Max,Int64Max)");
     Assert.AreEqual(BigInteger.Parse("91739176367857263082719902034485224119528064014300888465614024"), Euclid.LeastCommonMultiple(BigInteger.Parse("7305316061155559483748611586449542122662"), BigInteger.Parse("57377277362010117405715236427413896")), "Lcm(large)");
 }
コード例 #4
0
 public void GcdSupportsLargeInput()
 {
     Assert.AreEqual((BigInteger)Int32.MaxValue, Euclid.GreatestCommonDivisor(BigInteger.Zero, Int32.MaxValue), "Gcd(0,Int32Max)");
     Assert.AreEqual((BigInteger)Int64.MaxValue, Euclid.GreatestCommonDivisor(BigInteger.Zero, Int64.MaxValue), "Gcd(0,Int64Max)");
     Assert.AreEqual((BigInteger)1, Euclid.GreatestCommonDivisor((BigInteger)Int32.MaxValue, Int64.MaxValue), "Gcd(Int32Max,Int64Max)");
     Assert.AreEqual((BigInteger)(1 << 18), Euclid.GreatestCommonDivisor((BigInteger)(1 << 18), 1 << 20), "Gcd(1>>18,1<<20)");
     Assert.AreEqual((BigInteger)(1 << 18), Euclid.GreatestCommonDivisor((BigInteger)(1 << 18), 1 << 20), "Gcd(1>>18,1<<20)");
     Assert.AreEqual((BigInteger)4569031055798, Euclid.GreatestCommonDivisor(BigInteger.Parse("7305316061155559483748611586449542122662"), BigInteger.Parse("57377277362010117405715236427413896")), "Gcd(large)");
 }
コード例 #5
0
        public byte[] BlindData(Dictionary <string, object> blindKey, Dictionary <string, object> signKey, byte[] data)
        {
            var r          = BigInt.Parse(blindKey.GetString("r"));
            var e          = BigInt.Parse(signKey.GetString("e"));
            var n          = BigInt.Parse(signKey.GetString("n"));
            var multiplier = BigInt.Pow(r, (int)e);
            var m          = new BigInt(data);
            var result     = BigInt.ModPow(m * multiplier, 1, n);

            return(result.ToByteArray());
        }
コード例 #6
0
 public static BigNum FromString(string v)
 {
     try
     {
         return(new BigNum(BIM.Parse(v)));
     }
     catch (System.ArgumentException)
     {
         throw new FormatException();
     }
 }
コード例 #7
0
 private static BigInt RandomPrime(int size, Random random)
 {
     while (true)
     {
         var result = new CoreBigInt(size, random);
         if (result.IsProbablePrime(120))
         {
             return(BigInt.Parse(result.ToString()));
         }
     }
 }
コード例 #8
0
        public bool VerifyData(Dictionary <string, object> publicKey, byte[] data, byte[] signedData)
        {
            var e = BigInt.Parse(publicKey.GetString("e"));
            var n = BigInt.Parse(publicKey.GetString("n"));

            var s = new BigInt(signedData);

            var m      = BigInt.ModPow(s, e, n);
            var result = m.ToByteArray();

            return(result.SequenceEqual(data));
        }
コード例 #9
0
        public byte[] SignData(Dictionary <string, object> privateKey, byte[] data)
        {
            var d = BigInt.Parse(privateKey.GetString("d"));
            var n = BigInt.Parse(privateKey.GetString("n"));

            var m = new BigInt(data);

            var s      = BigInt.ModPow(m, d, n);
            var result = s.ToByteArray();

            return(result);
        }
コード例 #10
0
        public byte[] Encrypt(Dictionary <string, object> publicKey, byte[] data)
        {
            var e = BigInt.Parse(publicKey.GetString("e"));
            var n = BigInt.Parse(publicKey.GetString("n"));

            var m = new BigInt(data);

            var c      = BigInt.ModPow(m, e, n);
            var result = c.ToByteArray();

            return(result);
        }
コード例 #11
0
        public byte[] UnBlindData(Dictionary <string, object> blindKey, Dictionary <string, object> signKey, byte[] blindedData)
        {
            var r = BigInt.Parse(blindKey.GetString("r"));
            var e = BigInt.Parse(signKey.GetString("e"));
            var n = BigInt.Parse(signKey.GetString("n"));

            var inversedR = r.GetInversed(n);
            var m         = new BigInt(blindedData);
            var result    = BigInt.ModPow(m * inversedR, 1, n);

            return(result.ToByteArray());
        }
コード例 #12
0
        public byte[] Decrypt(Dictionary <string, object> privateKey, byte[] data)
        {
            var d = BigInt.Parse(privateKey.GetString("d"));
            var n = BigInt.Parse(privateKey.GetString("n"));

            var c = new BigInt(data);

            var m      = BigInt.ModPow(c, d, n);
            var result = m.ToByteArray();

            return(result);
        }
コード例 #13
0
        public async Task <string> CheckTransactionAndFindHackerContractAddr(string transaction, string contractAddr, decimal flagSumEth)
        {
            var trace = await TransactionTracer.TraceTransactionAsync(transaction, parityRpcUrl);

            if (trace == null)
            {
                log.Info($"Refused addr {contractAddr} hacking transaction candidate {transaction}: transaction trace returned zero result");
                return(null);
            }

            var moneyTransfersDict = trace
                                     .Select(item => item.action)
                                     .Select(action => new
            {
                fromAddr = action.fromAddr?.ToLowerInvariant(),
                toAddr   = action.toAddr?.ToLowerInvariant(),
                sum      = BigInteger.Parse("0" + (action.value?.Substring(2) ?? "0"), NumberStyles.AllowHexSpecifier)
            })
                                     .Where(mt => mt.fromAddr == contractAddr && mt.sum > 0)
                                     .GroupBy(mt => mt.toAddr)
                                     .ToDictionary(grouping => grouping.Key, grouping => grouping);

            if (moneyTransfersDict.Count != 1)
            {
                log.Info($"Refused addr {contractAddr} hacking transaction candidate {transaction}: has {moneyTransfersDict.Count} money recepients, but expected 1");
                return(null);
            }

            var hacker     = moneyTransfersDict.First();
            var hackerAddr = hacker.Key;

            BigInteger receivedSumInWei = 0;

            foreach (var mt in hacker.Value)
            {
                receivedSumInWei += mt.sum;
            }

            var ten        = new BigInteger(10);
            var weisInEth  = BigInteger.Pow(ten, 18);
            var flagSumWei = new BigInteger(flagSumEth) * weisInEth;

            if (receivedSumInWei < flagSumWei)
            {
                log.Info($"Refused addr {contractAddr} hacking transaction candidate {transaction}: hacker contract address {hackerAddr} received {receivedSumInWei} wei < expected {flagSumEth} eth");
                return(null);
            }

            return(hackerAddr);
        }
コード例 #14
0
 public void Init()
 {
     s1   = "1";
     s2   = "99999999999999999999999999999999";
     op1  = new BigInteger(s1);
     op2  = new BigInteger(s2);
     cop1 = MSBigInt.Parse(s1);
     cop2 = MSBigInt.Parse(s2);
     //cop1 = MSBigInt.Parse(op1.ToString());
     //cop2 = MSBigInt.Parse(op2.ToString());
     _timer.Reset();
     _nanoSecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
     Console.WriteLine("时间单位:Tick(每Tick为 " + _nanoSecPerTick + " 纳秒)");
     Console.WriteLine("1毫秒 = " + 1000000 / _nanoSecPerTick + " Tick");
 }
コード例 #15
0
        public void ExtendedGcdHandlesNormalInputCorrectly()
        {
            Assert.AreEqual((BigInteger)3, Euclid.ExtendedGreatestCommonDivisor(6, 15, out var x, out BigInteger y), "Egcd(6,15)");
            Assert.AreEqual((BigInteger)3, (6 * x) + (15 * y), "Egcd(6,15) -> a*x+b*y");

            Assert.AreEqual((BigInteger)3, Euclid.ExtendedGreatestCommonDivisor(-6, 15, out x, out y), "Egcd(-6,15)");
            Assert.AreEqual((BigInteger)3, (-6 * x) + (15 * y), "Egcd(-6,15) -> a*x+b*y");

            Assert.AreEqual((BigInteger)3, Euclid.ExtendedGreatestCommonDivisor(-6, -15, out x, out y), "Egcd(-6,-15)");
            Assert.AreEqual((BigInteger)3, (-6 * x) + (-15 * y), "Egcd(-6,-15) -> a*x+b*y");

            var a = BigInteger.Parse("7305316061155559483748611586449542122662");
            var b = BigInteger.Parse("57377277362010117405715236427413896");

            Assert.AreEqual((BigInteger)4569031055798, Euclid.ExtendedGreatestCommonDivisor(a, b, out x, out y), "Egcd(large)");
            Assert.AreEqual((BigInteger)4569031055798, (a * x) + (b * y), "Egcd(large) -> a*x+b*y");
            Assert.AreEqual((BigInteger)4569031055798, Euclid.ExtendedGreatestCommonDivisor(-a, b, out x, out y), "Egcd(-large)");
            Assert.AreEqual((BigInteger)4569031055798, (-a * x) + (b * y), "Egcd(-large) -> a*x+b*y");
        }
コード例 #16
0
 /** Find matching function definition for a function name and parameter
  *  value. The first definition is returned where (a) the name matches
  *  and (b) the formal parameter agrees if it is defined as constant.
  */
 private CommonTree findFunction(string name, BigInteger paramValue)
 {
     foreach (CommonTree f in functionDefinitions)
     {
         // Expected tree for f: ^(FUNC ID (ID | INT) expr)
         if (f.GetChild(0).Text.Equals(name))
         {
             // Check whether parameter matches
             CommonTree formalPar = (CommonTree)f.GetChild(1);
             if (formalPar.Token.Type == INT &&
                 !BigInteger.Parse(formalPar.Token.Text).Equals(paramValue))
             {
                 // Constant in formalPar list does not match actual value -> no match.
                 continue;
             }
             // Parameter (value for INT formal arg) as well as fct name agrees!
             return(f);
         }
     }
     return(null);
 }
コード例 #17
0
        public virtual string SignTransaction(string aTxData, ICurrencyTransaction aValidationInfo)
        {
            if (aValidationInfo.Outputs.Length > 2)
            {
                throw new ArgumentException("Invalid output.");
            }
            var lTxOutput    = aValidationInfo.Outputs.First();
            var lFromAddress = aValidationInfo.Inputs[0].Address.ToLower();
            var lToAddress   = lTxOutput.Address;
            var lKeyIndex    = FAddresses[lFromAddress];
            var lAmount      = lTxOutput.Amount;
            var lTokenData   = !string.IsNullOrEmpty(lTxOutput.Script) ? lTxOutput.Script : null;
            //var lNonceStr = Encoding.Default.GetString(HexStringToByteArray(aTxData)); //I removed this line because biginteger already accepts hex
            string     lCleanHexNonce = string.Concat("0", aTxData.Replace("0x", string.Empty));
            var        lNonce         = BigInteger.Parse(lCleanHexNonce, System.Globalization.NumberStyles.HexNumber);
            var        lGasLimit      = lTokenData == null ? 21000 : 60000;          // number of gass units you can use
            BigInteger lGasPrice      = aValidationInfo.TxFee / lGasLimit;
            var        lChainID       = aValidationInfo.CurrencyId == 10196 ? 3 : 1; //10196 is ropsten but this may be changed to a boolean into currency item
            var        lResult        = (new TransactionSigner()).SignTransaction(GetBinaryPrivateKey((int)lKeyIndex), lChainID, lToAddress, lAmount, lNonce, lGasPrice, lGasLimit, lTokenData);

            return(lResult);
        }
コード例 #18
0
 public static BigInteger Parse(string str)
 {
     return(new BigInteger(BigInt.Parse(str)));
 }
コード例 #19
0
 public LithpInteger(string value)
 {
     this.value = NumberType.Parse(value);
 }
コード例 #20
0
        public static BigFloat FromString(String s)
        {
            /*
             * String must be either of the format [-]0x^.^e*f*e*
             * or of the special value formats: 0NaN*e* 0nan*e* 0+oo*e* 0-oo*e*
             * Where ^ indicates a hexadecimal value and * indicates an integer value
             */

            int posLastE = s.LastIndexOf('e');

            int expSize = int.Parse(s.Substring(posLastE + 1));

            if (expSize <= 1)
            {
                throw new FormatException("Exponent size must be greater than 1");
            }

            int posLastF = s.LastIndexOf('f');
            int posSig   = posLastF + 1;

            if (posLastF == -1)
            {
                //NaN, +oo, -oo
                posSig = 4;
            }

            int sigSize = int.Parse(s.Substring(posSig, posLastE - posSig));

            if (sigSize <= 1)
            {
                throw new FormatException("Significand size must be greater than 1");
            }

            if (posLastF == -1)
            {
                //NaN, +oo, -oo
                return(new BigFloat(s.Substring(1, 3), sigSize, expSize));
            }

            bool isSignBitSet = s[0] == '-';

            int posX           = s.IndexOf('x');
            int posSecondLastE = s.LastIndexOf('e', posLastE - 1);

            string hexSig = s.Substring(posX + 1, posSecondLastE - (posX + 1));
            BIM    oldExp = BIM.Parse(s.Substring(posSecondLastE + 1, posLastF - (posSecondLastE + 1)));

            string binSig = string.Join(string.Empty,
                                        hexSig.Select(
                                            c => (c == '.' ? "." : Convert.ToString(Convert.ToInt32(c.ToString(), 16), 2).PadLeft(4, '0'))
                                            )
                                        );

            int posDec = binSig.IndexOf('.');

            binSig = binSig.Remove(posDec, 1);

            int posFirstOne = binSig.IndexOf('1');
            int posLastOne  = binSig.LastIndexOf('1');

            if (posFirstOne == -1)
            {
                return(new BigFloat(isSignBitSet, 0, 0, sigSize, expSize));
            }

            binSig = binSig.Substring(posFirstOne, posLastOne - posFirstOne + 1);

            BIM bias       = BIM.Pow(2, expSize - 1) - 1;
            BIM upperBound = 2 * bias + 1;

            BIM newExp = 4 * oldExp + bias + (posDec - posFirstOne - 1);

            if (newExp <= 0)
            {
                if (-newExp <= (sigSize - 1) - binSig.Length)
                {
                    binSig = new string('0', (int)-newExp) + binSig;
                    newExp = 0;
                }
            }
            else
            {
                binSig = binSig.Substring(1);
            }

            if (newExp < 0 || newExp >= upperBound)
            {
                throw new FormatException("The given exponent cannot fit in the bit size " + expSize);
            }

            binSig = binSig.PadRight(sigSize - 1, '0');

            if (binSig.Length > sigSize - 1)
            {
                throw new FormatException("The given significand cannot fit in the bit size " + (sigSize - 1));
            }

            BIM newSig = 0;

            foreach (char b in binSig)
            {
                if (b != '.')
                {
                    newSig <<= 1;
                    newSig  += b - '0';
                }
            }

            return(new BigFloat(isSignBitSet, newSig, newExp, sigSize, expSize));
        }
コード例 #21
0
ファイル: Numerics.cs プロジェクト: buptkang/MathCog
 public BigInt(string digits)
 {
     _num = FSBigInt.Parse(digits);
 }
コード例 #22
0
        /// <summary>
        /// 检查构造阶段是否能抛出正确的异常
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        private int CheckInput(int i)
        {
            bool      msFailed     = false;
            bool      ulyFailed    = false;
            Exception msException  = null;
            Exception ulyException = null;

            if (iop1s[i].Length > 50)
            {
                Console.WriteLine("op1:" + iop1s[i].Substring(0, 10) + "......" + iop1s[i].Substring(iop1s[i].Length - 10, 10) + "[共" + iop1s[i].Length + "位]");
            }
            else
            {
                Console.WriteLine("op1:" + iop1s[i]);
            }

            if (iop2s[i].Length > 50)
            {
                Console.WriteLine("op2:" + iop2s[i].Substring(0, 10) + "......" + iop2s[i].Substring(iop2s[i].Length - 10, 10) + "[共" + iop2s[i].Length + "位]");
            }
            else
            {
                Console.WriteLine("op2:" + iop2s[i]);
            }

            try
            {
                cop1 = MSBigInt.Parse(iop1s[i]);
                cop2 = MSBigInt.Parse(iop2s[i]);
            }
            catch (Exception e)
            {
                msException = e;
                msFailed    = true;
                Console.WriteLine("System.Numerics.BigInteger抛出解析异常:{0}", e.Message);
            }
            try
            {
                op1 = new BigInteger(iop1s[i]);
                op2 = new BigInteger(iop2s[i]);
            }
            catch (Exception e)
            {
                ulyException = e;
                ulyFailed    = true;
                Console.WriteLine("Uly.Numerics.BigInteger抛出解析异常:{0}", e.Message);
            }
            if (ulyFailed)
            {
                if (!msFailed)
                {
                    //微软能正常解析而本库不能,直接失败
                    Assert.Fail("目标库的行为与对照组不一致,于第{0}组测试失败:{1}", i, info[i]);
                }
                else
                {
                    //两种库都不能解析,必须抛出相同的异常
                    Assert.AreSame(msException.GetType(), ulyException.GetType(), string.Format("目标库的抛出的异常与对照组不一致,于第{0}组测试失败:{1}", i, info[i]));
                    if (msException.GetType() == ulyException.GetType())
                    {
                        Console.WriteLine("目标库与对照组抛出了相同的异常,测试成功:{0} VS {1}", ulyException.Message, msException.Message);
                        return(-1);  //跳过此组测试的剩余内容
                    }
                    Assert.Fail("目标库的行为与对照组不一致,于第{0}组测试失败:{1}", i, info[i]);
                }
            }
            else
            {
                if (msFailed)
                {
                    //本库能解析而微软库不能
                    Console.WriteLine("对照组无法解析此组数据!尝试将目标库解析后的数据赋值给对照组...");
                    try
                    {
                        cop1 = MSBigInt.Parse(op1.ToString());
                        cop2 = MSBigInt.Parse(op2.ToString());
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("对照组已经无法解析此组数据!缺乏对照组,本轮测试将跳过!");
                        return(0);//只使用目标库运算
                    }
                }
            }
#if ONLY_TARGET
            return(0); //只测试目标库
#endif
            return(1); //两组数据均没有问题
        }