示例#1
0
        public static bool Base58CheckDecode2(this string input)
        {
            byte[] buffer = null;
            try
            {
                buffer = Base58.Decode(input);

                byte[] buffer2 = new byte[buffer.Length - 4];
                Buffer.BlockCopy(buffer, 0, buffer2, 0, buffer2.Length);

                if (buffer.Length < 4)
                {
                    throw new FormatException();
                }
                string hash1    = CryptoHelper.Sha256(buffer2.ToHexString());
                byte[] checksum = CryptoHelper.Sha256(hash1).HexToBytes();
                if (!buffer.Skip(buffer.Length - 4).SequenceEqual(checksum.Take(4)))
                {
                    return(false);
                }
                var ret = buffer.Take(buffer.Length - 4).ToArray();
                Array.Clear(buffer, 0, buffer.Length);
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
示例#2
0
        private static void TransferInfo(HttpMessage httpMessage, string ruleIP)
        {
            string timestamp  = (TimeHelper.Now()).ToString();
            string cmd        = "transfer";                                             //1
            string type       = cmd;                                                    //2
            string nonce      = Program.nonce;
            string addressIn  = Wallet.ToAddress(Program.wallet.keys[0].publickey);     //3
            string addressOut = httpMessage.map["1"];                                   //4
            string amount     = (float.Parse(httpMessage.map["2"]) * 10000).ToString(); //5
            string data       = "";                                                     //6
            string fee        = (httpMessage.map.Count == 5 ? httpMessage.map["3"] : "0");
            string depend     = "";                                                     //7
            string hashdata   = "transfer#" + nonce + "#" + addressIn + "#" + addressOut + "#" + amount + "#" + data + "#" + depend + "#" + timestamp;
            string hash       = CryptoHelper.Sha256(hashdata);                          //8
            string sign       = GetSign(hash).ToLower();                                //9

            httpMessage.map.Clear();
            httpMessage.map.Add("cmd", cmd);
            httpMessage.map.Add("type", type);
            httpMessage.map.Add("hash", hash);
            httpMessage.map.Add("nonce", nonce);
            httpMessage.map.Add("addressIn", addressIn);
            httpMessage.map.Add("addressOut", addressOut);
            httpMessage.map.Add("amount", amount);
            httpMessage.map.Add("data", data);
            httpMessage.map.Add("depend", depend);
            httpMessage.map.Add("sign", sign);
            httpMessage.map.Add("fee", fee);
            httpMessage.map.Add("timestamp", timestamp);
        }
示例#3
0
 static public string ToHash(this Block This, string r = null)
 {
     //if (r != null && r != "")
     //    return CryptoHelper.Sha256((CryptoHelper.Sha256(This.ToString()) + r));
     //return CryptoHelper.Sha256((CryptoHelper.Sha256(This.ToString()) + This.random));
     return(BlockDag.ToHash(This.height, CryptoHelper.Sha256(This.ToString()), r ?? This.random));
 }
示例#4
0
        public Dictionary <string, BlockSub> MinerReward_SOLO()
        {
            if (httpPool != null)
            {
                Dictionary <string, BlockSub>  minerTransfer = new Dictionary <string, BlockSub>();
                Dictionary <string, MinerTask> miners        = httpPool.GetMinerReward(out long miningHeight);
                if (miners != null && miningHeight + 5 < httpPool.height)
                {
                    string ownerAddress = Wallet.GetWallet().GetCurWallet().ToAddress();

                    var mcblk = BlockChainHelper.GetMcBlock(miningHeight);
                    if (mcblk != null && mcblk.Address == ownerAddress)
                    {
                        var miner = miners.Values.FirstOrDefault(c => c.random == mcblk.random);
                        if (miner != null)
                        {
                            var transfer = new BlockSub();
                            transfer.addressIn  = ownerAddress;
                            transfer.addressOut = miner.address;
                            transfer.type       = "transfer";
                            transfer.amount     = Consensus.GetReward(miningHeight).ToString();
                            transfer.data       = CryptoHelper.Sha256($"{mcblk.hash}_{ownerAddress}_{miner.address}_{transfer.amount}_Reward_SOLO");
                            minerTransfer.Add(transfer.addressOut, transfer);

                            transferProcess.AddTransferHandle(ownerAddress, miner.address, transfer.amount, transfer.data);
                            transferProcess.SaveTransferToDB();
                        }
                    }
                    httpPool.DelMiner(miningHeight);
                    return(minerTransfer);
                }
            }
            return(null);
        }
示例#5
0
        static public string ToHash(long height, string hashmining, string random)
        {
            if (string.IsNullOrEmpty(hashmining) || string.IsNullOrEmpty(random))
            {
                return("");
            }

            if (height <= 141222)
            {
                Init();
                V2_0_0_right = V2_0_0_right != BigInteger.Zero ? V2_0_0_right : BigInteger.Parse((dag.Length - randomDag.Value.Length).ToString());

                var hash1 = _ToDag(random);
                var hash2 = _ToDag(CryptoHelper.Sha256(hash1).Substring(hashmining.Length - random.Length));
                var hash3 = CryptoHelper.Sha256(hashmining + random + hash1 + hash2);
                return(hash3);
            }
            else
            {
                var hash1 = CryptoHelper.Sha256(hashmining + random);
                var hash2 = RandomXSharp.RandomX.CaculateHash(hash1);
                var hash3 = CryptoHelper.Sha256(hash2);
                return(hash3);
            }
        }
示例#6
0
        public static string GetContractAddress(BlockSub transfer)
        {
            string address = string.IsNullOrEmpty(transfer.addressOut)
                            ? Wallet.ToAddress(CryptoHelper.Sha256(Encoding.UTF8.GetBytes($"{transfer.addressIn}#{transfer.data}#{transfer.timestamp}#{FileHelper.GetFileData($"./Data/Contract/{transfer.depend}.lua")}")))
                            : transfer.addressOut;

            return(address);
        }
示例#7
0
 static public string ToHash(this Block This, string r = null)
 {
     if (r != null && r != "")
     {
         return(CryptoHelper.Sha256((CryptoHelper.Sha256(This.ToString()) + r)));
     }
     return(CryptoHelper.Sha256((CryptoHelper.Sha256(This.ToString()) + This.random)));
 }
示例#8
0
        public Dictionary <string, BlockSub> GetMinerReward_SOLO(long minHeight, long maxHeight)
        {
            Dictionary <string, BlockSub> minerTransfer = new Dictionary <string, BlockSub>();

            if (httpPool != null)
            {
                string addressIn = Wallet.GetWallet().GetCurWallet().ToAddress();

                for (long rewardheight = minHeight; rewardheight < maxHeight; rewardheight++)
                {
                    Dictionary <string, MinerTask> miners = null;
                    using (DbSnapshot snapshot = PoolDBStore.GetSnapshot())
                    {
                        string json = snapshot.Get("Pool_H2_" + rewardheight);
                        if (!string.IsNullOrEmpty(json))
                        {
                            miners = JsonHelper.FromJson <Dictionary <string, MinerTask> >(json);
                        }
                    }

                    if (miners != null)
                    {
                        var mcblk = GetMcBlock(rewardheight);
                        if (mcblk != null && mcblk.Address == ownerAddress)
                        {
                            var miner = miners.Values.FirstOrDefault(c => c.random.IndexOf(mcblk.random) != -1);
                            if (miner != null)
                            {
                                BigFloat reward = new BigFloat(Consensus.GetReward(rewardheight));
                                reward = reward * (1.0f - GetServiceFee());

                                var transfer = new BlockSub();
                                transfer.addressIn  = addressIn;
                                transfer.addressOut = miner.address;
                                string pay = BigHelper.Round8(reward.ToString());

                                if (minerTransfer.TryGetValue(miner.address, out transfer))
                                {
                                    transfer.amount = BigHelper.Add(transfer.amount, pay);
                                }
                                else
                                {
                                    transfer            = new BlockSub();
                                    transfer.addressIn  = addressIn;
                                    transfer.addressOut = miner.address;
                                    transfer.amount     = BigHelper.Sub(pay, "0.002"); // 扣除交易手续费
                                    transfer.type       = "100%";                      // 有效提交百分比
                                    transfer.data       = CryptoHelper.Sha256($"{mcblk.hash}_{maxHeight}_{ownerAddress}_{miner.address}_Reward_SOLO");
                                    minerTransfer.Add(transfer.addressOut, transfer);
                                }
                            }
                        }
                    }
                }
            }
            return(minerTransfer);
        }
示例#9
0
 public static string ToAddress(byte[] publickey)
 {
     //byte[] hash = publickey.Sha256().RIPEMD160();
     byte[] hash = CryptoHelper.Sha256(publickey.ToHexString()).ToByteArray().RIPEMD160();
     byte[] data = new byte[21];
     data[0] = 1;
     Buffer.BlockCopy(hash, 0, data, 1, 20);
     return(data.Base58CheckEncode());
 }
示例#10
0
        public WalletKey Create()
        {
            WalletKey walletKey = new WalletKey();
            string    input     = Wallet.Inst.Input("Please enter random word: ");

            walletKey.random = CryptoHelper.Sha256(Seek().ToHexString() + "#" + input).HexToBytes();
            ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, walletKey.random);
            this.keys.Add(walletKey);
            return(walletKey);
        }
示例#11
0
        static public string ToHash(long height, string hashmining, string random)
        {
            Init();
            V2_0_0_right = V2_0_0_right != BigInteger.Zero ? V2_0_0_right : BigInteger.Parse((dag.Length - randomDag.Length).ToString());

            var hash1 = _ToDag(random);
            var hash2 = _ToDag(CryptoHelper.Sha256(hash1).Substring(hashmining.Length - random.Length));

            return(CryptoHelper.Sha256(hashmining + random + hash1 + hash2));
            //return CryptoHelper.Sha256(hashmining + random);
        }
示例#12
0
        public WalletKey Create()
        {
            WalletKey walletKey = new WalletKey();

            walletKey.random = Seek();
            string seed = CryptoHelper.Sha256(walletKey.random.ToHexString() + "#" + passwords);

            ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, seed.HexToBytes());
            this.keys.Add(walletKey);
            return(walletKey);
        }
示例#13
0
        // http://127.0.0.1:8088/mining?cmd=Submit
        public void OnSubmit(HttpMessage httpMessage)
        {
            // submit
            Dictionary <string, string> map = new Dictionary <string, string>();

            try
            {
                map.Add("report", "refuse");

                long   minerHeight = long.Parse(httpMessage.map["height"]);
                string address     = httpMessage.map["address"];
                string number      = httpMessage.map["number"];
                if (minerHeight == height && hashmining != "")
                {
                    MinerTask minerTask = GetMyTaskID(minerHeight, address, number, httpMessage.map["taskid"]);
                    if (minerTask != null && TimeHelper.time - minerTask.time > 0.1)
                    {
                        minerTask.time = TimeHelper.time;
                        string random = httpMessage.map["random"];
                        string hash   = CryptoHelper.Sha256(hashmining + random);
                        double diff   = Helper.GetDiff(hash);
                        if (diff > minerTask.diff)
                        {
                            minerTask.diff          = diff;
                            minerTask.random        = random;
                            minerTask.power_average = httpMessage.map["average"];
                            map.Add("report", "accept");
                        }
                    }
                }

                if (minerHeight != height && hashmining != "")
                {
                    MinerTask minerTask = NewNextTakID(height, address, number);
                    // new task
                    map.Add("height", height.ToString());
                    map.Add("hashmining", hashmining);
                    map.Add("taskid", minerTask.taskid);
                    map.Add("power", power);
                    if (minerTask.number != number)
                    {
                        map.Add("number", minerTask.number);
                    }
                }
            }
            catch (Exception)
            {
                map.Remove("report");
                map.Add("report", "error");
            }
            httpMessage.result = JsonHelper.ToJson(map);
        }
示例#14
0
        public void GetMnemonicWord(HttpMessage httpMessage)
        {
            if (!GetParam(httpMessage, "1", "passwords", out string passwords))
            {
                httpMessage.result = "command error! \nexample: getmnemonic password";
                return;
            }

            var    walletKey  = Wallet.GetWallet().GetCurWallet();
            string randomSeed = CryptoHelper.Sha256(walletKey.random.ToHexString() + "#" + passwords);

            httpMessage.result = randomSeed;
        }
示例#15
0
        public void Mining(Block blk, string hashmining)
        {
            string random = System.Guid.NewGuid().ToString("N").Substring(0, 16);
            string hash   = CryptoHelper.Sha256(hashmining + random);

            double diff = Helper.GetDiff(hash);

            if (diff > diff_max)
            {
                diff_max   = diff;
                blk.hash   = hash;
                blk.random = random;
            }
        }
示例#16
0
        static string _ToDag(string random)
        {
            var left   = BigInteger.Parse("0" + random, System.Globalization.NumberStyles.HexNumber);
            var right  = BigInteger.Remainder(left, V2_0_0_right).ToString();
            var offset = long.Parse(right);

            int dagIndex = 0;

            for (int jj = 0; jj < randomDag.Value.Length; jj++, dagIndex++)
            {
                randomDag.Value[jj] = dag[offset + dagIndex];
            }

            return(CryptoHelper.Sha256(random + randomDag.Value.ToStr()));
        }
示例#17
0
        static public void Test()
        {
            string info = "";

            for (int i = 0; i < 100; i++)
            {
                WalletKey walletKey = new WalletKey();
                walletKey.random = Seek();
                string seed = CryptoHelper.Sha256(walletKey.random.ToHexString() + "#" + "123");
                ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, seed.HexToBytes());

                string address = Wallet.ToAddress(walletKey.publickey);
                info += address + "\n";
            }
            Log.Info("Address    \n" + info);
        }
示例#18
0
        public string ToHash()
        {
            string str_extend = "";

            if (extend != null)
            {
                str_extend += "#";
                for (int ii = 0; ii < extend.Count; ii++)
                {
                    str_extend = $"{str_extend}#{extend[ii]}";
                }
                str_extend += "#";
            }
            string temp = $"{type}#{nonce}#{addressIn}#{addressOut}#{amount}#{data}#{depend}#{timestamp}#{remarks}{str_extend}";

            return(CryptoHelper.Sha256(temp));
        }
示例#19
0
 static public void Init()
 {
     if (dag == null)
     {
         dag = new byte[V2_0_0_size];
         var hash     = CryptoHelper.Sha256("SmartX_DAG 2021_03_18 21:43:56");
         var count    = dag.Length / hash.Length;
         int dagIndex = 0;
         for (int ii = 0; ii < count; ii++)
         {
             hash = CryptoHelper.Sha256(hash);
             for (int jj = 0; jj < hash.Length; jj++)
             {
                 dag[dagIndex++] = (byte)hash[jj];
             }
         }
     }
 }
示例#20
0
        public static string Base58CheckEncode(this byte[] data)
        {
            string hash1 = CryptoHelper.Sha256(data.ToHexString());

            byte[] checksum = CryptoHelper.Sha256(hash1).HexToBytes();
            byte[] buffer   = new byte[data.Length + 4];
            Buffer.BlockCopy(data, 0, buffer, 0, data.Length);
            Buffer.BlockCopy(checksum, 0, buffer, data.Length, 4);
            var ret = Base58.Encode(buffer);

            //Log.Info("Base58CheckEncodedata " + data.ToHexString() );
            //Log.Info("Base58CheckEncode1 " + hash1);
            //Log.Info("Base58CheckEncode2 " + CryptoHelper.Sha256(hash1));
            //Log.Info("Base58CheckEncode3 " + buffer.ToHexString() );
            //Log.Info("Base58CheckEncoderet " + ret );

            Array.Clear(buffer, 0, buffer.Length);
            return(ret);
        }
示例#21
0
        public override void Start()
        {
            rule = Entity.Root.GetComponent <Rule>();
            ComponentNetMsg componentNetMsg = Entity.Root.GetComponent <ComponentNetMsg>();

            componentNetMsg.registerMsg(NetOpcode.P2P_NewBlock, P2P_NewBlock_Handle);

            string genesisText = File.ReadAllText("./Data/genesisBlock.dat");
            Block  blk         = JsonHelper.FromJson <Block>(genesisText);

            superAddress = blk.Address;

            long.TryParse(Entity.Root.GetComponent <LevelDBStore>().Get("UndoHeight"), out long UndoHeight);
            if (UndoHeight == 0)
            {
                if (true)
                {
                    blockMgr.AddBlock(blk);
                    ApplyGenesis(blk);
                }
            }

            string consData = Base58.Encode(FileHelper.GetFileData("./Data/Contract/RuleContract_v1.0.lua").ToByteArray());

            consAddress = Wallet.ToAddress(CryptoHelper.Sha256(Encoding.UTF8.GetBytes(consData)));

            using (DbSnapshot snapshot = levelDBStore.GetSnapshot())
            {
                LuaVMScript luaVMScript = new LuaVMScript()
                {
                    script = FileHelper.GetFileData("./Data/Contract/RuleContract_curr.lua").ToByteArray()
                };
                snapshot.Contracts.Add(consAddress, luaVMScript);
                snapshot.Commit();
            }
            ruleInfos = luaVMEnv.GetRules(consAddress, UndoHeight);

            if (bRun)
            {
                Run();
            }
        }
示例#22
0
        static public void Mining(object data)
        {
            Miner This = data as Miner;

            while (true)
            {
                if (This.hashmining != "")
                {
                    string randomTemp;
                    if (This.taskid != "")
                    {
                        randomTemp = This.taskid + System.Guid.NewGuid().ToString("N").Substring(0, 13);
                    }
                    else
                    {
                        randomTemp = System.Guid.NewGuid().ToString("N").Substring(0, 16);
                    }

                    if (randomTemp == "0")
                    {
                        Log.Debug("random==\"0\"");
                    }

                    string hash = CryptoHelper.Sha256(This.hashmining + randomTemp);

                    double diff = Helper.GetDiff(hash);
                    if (diff > This.diff_max)
                    {
                        This.diff_max = diff;
                        This.random   = randomTemp;
                    }
                }
                else
                {
                    System.Threading.Thread.Sleep(100);
                }
            }
        }
示例#23
0
        int OpenWallet(string password)
        {
            passwords = password;
            try
            {
                string[] lines = File.ReadAllLines(walletFile, System.Text.Encoding.Default);
                for (int i = 0; i < lines.Length; i++)
                {
                    string[] array = lines[i].Split(',');
                    if (array.Length == 2)
                    {
                        string    seed      = CryptoHelper.Sha256(array[0] + "#" + password);
                        WalletKey walletKey = new WalletKey();
                        ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, seed.HexToBytes());

                        if (walletKey.ToAddress() != array[1])
                        {
                            return(-2);
                        }

                        walletKey.random = array[0].HexToBytes();
                        keys.Add(walletKey);
                    }
                    else
                    if (array.Length == 1)
                    {
                        curIndex = int.Parse(array[0]);
                    }
                }
            }
            catch (Exception)
            {
                return(-1);
            }
            return(1);
        }
示例#24
0
 static public string Sha256(string data)
 {
     return(CryptoHelper.Sha256(data));
 }
示例#25
0
        public string ToHash()
        {
            string temp = $"{type}#{notice}#{addressIn}#{addressOut}#{amount}#{data}#{depend}";

            return(CryptoHelper.Sha256(temp));
        }
示例#26
0
        // Miner reward, only after confirming that it cannot be rolled back
        public Dictionary <string, BlockSub> GetMinerReward_PPLNS(long minHeight, long maxHeight)
        {
            Dictionary <string, BlockSub> minerTransfer = new Dictionary <string, BlockSub>();

            if (httpPool != null)
            {
                string addressIn = Wallet.GetWallet().GetCurWallet().ToAddress();

                for (long rewardheight = minHeight; rewardheight < maxHeight; rewardheight++)
                {
                    Dictionary <string, MinerTask> miners = null;
                    using (DbSnapshot snapshot = PoolDBStore.GetSnapshot())
                    {
                        string json = snapshot.Get("Pool_H2_" + rewardheight);
                        if (!string.IsNullOrEmpty(json))
                        {
                            miners = JsonHelper.FromJson <Dictionary <string, MinerTask> >(json);
                        }
                    }

                    if (miners != null)
                    {
                        var mcblk = GetMcBlock(rewardheight);
                        if (mcblk == null)
                        {
                            throw new Exception($"GetMcBlock({rewardheight}) return null");
                        }

                        if (mcblk != null && mcblk.Address == ownerAddress)
                        {
                            double reward = Consensus.GetReward(rewardheight);
                            reward = reward * (1.0f - GetServiceFee());

                            var miner = miners.Values.FirstOrDefault(c => c.random.IndexOf(mcblk.random) != -1);
                            if (miner == null)
                            {
                                continue;
                            }

                            // Total power
                            double powerSum = 0;
                            var    Values   = miners.Values.ToList();
                            for (var ii = 0; ii < Values.Count; ii++)
                            {
                                var dic = Values[ii];
                                if (string.IsNullOrEmpty(dic.address))
                                {
                                    continue;
                                }
                                double power = CalculatePower.Power(dic.diff);
                                if (power < HttpPool.ignorePower)
                                {
                                    continue;
                                }
                                powerSum += power;
                            }

                            // Reward for participation
                            BlockSub transfer = null;
                            for (var ii = 0; ii < Values.Count; ii++)
                            {
                                var dic = Values[ii];
                                if (string.IsNullOrEmpty(dic.address))
                                {
                                    continue;
                                }
                                double power = CalculatePower.Power(dic.diff);
                                double pay   = Math.Round(power * reward / powerSum, 8);

                                if (minerTransfer.TryGetValue(dic.address, out transfer))
                                {
                                    if (power < HttpPool.ignorePower)
                                    {
                                        transfer.height += 1; // 这里表示无效提交数
                                        continue;
                                    }

                                    transfer.nonce += 1; // 这里表示有效提交数
                                    transfer.amount = BigHelper.Add(transfer.amount, pay.ToString("N8"));
                                }
                                else
                                if (pay >= 0.002)
                                {
                                    transfer            = new BlockSub();
                                    transfer.nonce      = 1; // 这里表示有效提交数
                                    transfer.addressIn  = addressIn;
                                    transfer.addressOut = dic.address;
                                    transfer.amount     = BigHelper.Sub(pay.ToString("N8"), "0.002"); // 扣除交易手续费
                                    transfer.data       = CryptoHelper.Sha256($"{mcblk.hash}_{maxHeight}_{ownerAddress}_{dic.address}_MinerReward");
                                    if (power < HttpPool.ignorePower)
                                    {
                                        transfer.height += 1; // 这里表示无效提交数
                                        continue;
                                    }

                                    minerTransfer.Add(transfer.addressOut, transfer);
                                }
                            }
                        }
                    }
                }

                // 有效提交次数越多收益越高
                var totalAmount1 = "0"; // 总账1
                var totalAmount2 = "0"; // 总账2
                foreach (var transfer in minerTransfer.Values)
                {
                    try
                    {
                        totalAmount1 = BigHelper.Add(totalAmount1, transfer.amount);
                        var totalSubmit = transfer.nonce + transfer.height;
                        var share       = (float)transfer.nonce / (float)totalSubmit;
                        transfer.type    = $"{Math.Round(share * 100, 2)}%"; // 有效提交百分比
                        share           *= share;
                        transfer.remarks = BigHelper.Mul(share.ToString(), transfer.amount);
                        totalAmount2     = BigHelper.Add(totalAmount2, transfer.remarks);
                    }
                    catch (Exception)
                    {
                        transfer.type    = "0%";
                        transfer.remarks = "0";
                    }
                }

                var totalAmount3 = "0"; // 总账3
                foreach (var transfer in minerTransfer.Values)
                {
                    try
                    {
                        transfer.amount = BigHelper.Div(BigHelper.Mul(transfer.remarks, totalAmount1), totalAmount2);
                        totalAmount3    = BigHelper.Add(totalAmount3, transfer.amount);
                    }
                    catch (Exception)
                    {
                    }
                }

                //if (BigHelper.Greater(BigHelper.Abs(BigHelper.Sub(totalAmount1, totalAmount3)), "0.002", true))
                //{
                //    Log.Warning($"|totalAmount1 - totalAmount3| > 0.002 {BigHelper.Sub(totalAmount1, totalAmount3)}");
                //}
            }
            return(minerTransfer);
        }
示例#27
0
 static public string ToHashMining(this Block This)
 {
     return(CryptoHelper.Sha256(This.ToString()));
 }
示例#28
0
        public async void Run()
        {
            Program.DisbleQuickEditMode();
            Console.Clear();
            Console.CursorVisible = false;
            Console.Title         = $" address:{address} number:{number}  poolUrl:{poolUrl}";

            await Task.Delay(1000);

            //创建后台工作线程
            for (int ii = 0; ii < 16; ii++)
            {
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Mining));
                thread.IsBackground = true;//设置为后台线程
                thread.Start(this);
            }

            HttpMessage quest = new HttpMessage();

            quest.map = new Dictionary <string, string>();

            while (true)
            {
                try
                {
                    if (timePass.IsPassSet())
                    {
                        string hash = CryptoHelper.Sha256(hashmining + random);
                        Log.Debug($"\n height:{height}, taskid:{taskid}, random:{random}, diff:{diff_max}, power:{calculatePower.GetPower()} hash:{hash}");
                    }

                    quest.map.Clear();
                    quest.map.Add("cmd", "submit");
                    quest.map.Add("height", height.ToString());
                    quest.map.Add("address", address);
                    quest.map.Add("number", number);
                    quest.map.Add("random", random);
                    quest.map.Add("taskid", taskid);
                    HttpMessage result = await ComponentNetworkHttp.Query(poolUrl, quest);

                    if (result.map != null)
                    {
                        if (result.map.ContainsKey("taskID"))
                        {
                            long.TryParse(result.map["height"], out long tempheight);
                            taskid = result.map["taskID"];
                            string temphash = result.map["hashmining"];
                            if (temphash == null || temphash == "" || temphash != hashmining)
                            {
                                if (diff_max != 0)
                                {
                                    calculatePower.Insert(diff_max);
                                }

                                diff_max   = 0;
                                hashmining = temphash;
                                height     = tempheight;
                                random     = "";
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
                await Task.Delay(1000);
            }
        }
示例#29
0
        public static async System.Threading.Tasks.Task OrderAsync(HttpMessage httpMessage)
        {
            Wallet.Inst = null;
            if (httpMessage.map["0"] == "importkey")
            {
                if (!GetParam(httpMessage, "1", "1", out string privatekey))
                {
                    httpMessage.result = "command error! \nexample: import key privatekey";
                    return;
                }
                string address = AddKeyBag(privatekey, Program.keyBag);
                httpMessage.result = $" {address}";
            }
            else if (httpMessage.map["0"] == "showip")
            {
                httpMessage.result = JsonHelper.ToJson(Program.ruleIP);
            }
            else if (httpMessage.map["0"] == "openwallet")
            {
                Wallet wallet = new Wallet();
                if (httpMessage.map.Count == 2)
                {
                    httpMessage.map.Add("1", "./smartx-wallet.json");
                }
                if (Program.wallet.keys.Count > 0)
                {
                    httpMessage.result = "please close wallet first!";
                    return;
                }
                try
                {
                    string path    = httpMessage.map["1"];
                    Wallet wallet1 = Wallet.GetWallet(path);
                    wallet = wallet1;
                }
                catch (Exception e)
                {
                    httpMessage.result = "Please check your path";
                    return;
                }


                if (wallet == null)
                {
                    httpMessage.result = "Password error";
                    return;
                }
                if (Program.keyBag.Count > 0)
                {
                    if (!Program.keyBag.ContainsKey(wallet.keys[0].ToAddress()))
                    {
                        Program.keyBag.Add(Wallet.ToAddress(wallet.keys[0].publickey), wallet.keys[0]);
                    }
                }
                else
                {
                    Program.keyBag.Add(Wallet.ToAddress(wallet.keys[0].publickey), wallet.keys[0]);
                }
                Program.wallet = wallet;
                //string random = Program.wallet.keys[0].random.ToHex();
                //string nonce="0";
                string nonce = await GetNonceAsync(Wallet.ToAddress(Program.wallet.keys[0].publickey), httpMessage, Program.ruleIP);//0

                if (nonce == "INVALID URL, set the correct url" || nonce == "false")
                {
                    httpMessage.result = nonce;
                    return;
                }
                Program.nonce = (int.Parse(nonce) + 1).ToString();
                //Console.WriteLine(Program.nonce);
                httpMessage.result = Wallet.ToAddress(Program.wallet.keys[0].publickey) + " open";
            }
            else if (httpMessage.map["0"] == "setwallet")
            {
                if (!GetParam(httpMessage, "1", "address", out string address))
                {
                    httpMessage.result = "command error! \nexample: setwallet address";
                    return;
                }
                WalletKey key = new WalletKey();
                if (Program.keyBag.Count > 0)
                {
                    if (Program.keyBag.ContainsKey(address))
                    {
                        key = Program.keyBag[address];
                    }
                    else
                    {
                        httpMessage.result = "The address isn't in the key bag";
                        return;
                    }
                }
                else
                {
                    httpMessage.result = "The address isn't in the key bag";
                    return;
                }

                if (Program.wallet.keys.Count != 0)
                {
                    httpMessage.result = "please close wallet first!";
                    return;
                }
                Program.wallet.keys.Add(key);
                string nonce = await GetNonceAsync(address, httpMessage, Program.ruleIP);//0

                if (nonce == "INVALID URL, set the correct url" || nonce == "false")
                {
                    httpMessage.result = nonce;
                    return;
                }
                Program.nonce      = (int.Parse(nonce) + 1).ToString();
                httpMessage.result = $"{address} set";
            }
            else if (httpMessage.map["0"] == "list")
            {
                List <string> list = new List <string>();
                foreach (KeyValuePair <string, WalletKey> k in Program.keyBag)
                {
                    list.Add(k.Key);
                }
                httpMessage.result = JsonHelper.ToJson(list);
            }
            else if (httpMessage.map["0"] == "closewallet")
            {
                Wallet.Inst        = null;
                Program.wallet     = new Wallet();
                Program.nonce      = "";
                httpMessage.result = "wallet closed";
            }
            else if (httpMessage.map["0"] == "getprivatekey")
            {
                if (Program.wallet.keys.Count != 0)
                {
                    httpMessage.result = JsonHelper.ToJson(Program.wallet.keys[0].random.ToHexString());
                }
                else
                {
                    httpMessage.result = "please set wallet";
                }
            }
            else if (httpMessage.map["0"] == "exportkey")
            {
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "please set wallet";
                    return;
                }
                if (httpMessage.map.Count <= 2)
                {
                    File.WriteAllText("./private.json", Program.wallet.keys[0].random.ToHexString());
                    httpMessage.result = $"export key  successful";
                    return;
                }
                else if (Program.wallet.keys.Count > 0)
                {
                    try
                    {
                        File.WriteAllText(httpMessage.map["1"] + "/private.json", Program.wallet.keys[0].random.ToHexString());
                        httpMessage.result = $"export key  successful";
                    }
                    catch (Exception)
                    {
                        httpMessage.result = "Please check the path";
                        return;
                    }
                }
                else
                {
                    httpMessage.result = "Please set the wallet first";
                }
            }
            else if (httpMessage.map["0"] == "clear")
            {
                Console.Clear();
            }
            else if (httpMessage.map["0"] == "transfer")
            {
                if (httpMessage.map.Count <= 3)
                {
                    Console.WriteLine("transfer error example transfer addressOut amount fee");
                    return;
                }
                if (Program.wallet.keys.Count == 0)
                {
                    httpMessage.result = "Please set the wallet first";
                    return;
                }
                if (!Wallet.CheckAddress(httpMessage.map["1"]))
                {
                    httpMessage.result = "Please check addressOut";
                    return;
                }
                TransferInfo(httpMessage, Program.ruleIP);
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                if (result.result.Contains("true"))
                {
                    Program.nonce      = (int.Parse(Program.nonce) + 1).ToString();
                    httpMessage.result = result.result + " " + httpMessage.map["hash"];
                }
                else
                {
                    httpMessage.result = "false";
                }
            }
            else if (httpMessage.map["0"] == "createkey")
            {
                Console.WriteLine("Please enter random word: ");
                string    input     = Console.ReadLine();
                WalletKey walletKey = new WalletKey();
                walletKey.random = CryptoHelper.Sha256(Seek().ToHexString() + "#" + input).HexToBytes();
                ed25519.ed25519_create_keypair(walletKey.publickey, walletKey.privatekey, walletKey.random);
                if (walletKey.random != null)
                {
                    Dictionary <string, string> walletinfo = new Dictionary <string, string>();
                    walletinfo.Add("address", walletKey.ToAddress());
                    walletinfo.Add("privatekey", walletKey.random.ToHexString());
                    httpMessage.result = JsonHelper.ToJson(walletinfo);
                    return;
                }
                httpMessage.result = "createkey error";
            }
            else if (httpMessage.map["0"] == "createwallet")
            {
                OnCreat(httpMessage);
            }
            else if (httpMessage.map["0"] == "mempool")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "getlastblock")
            {
                try
                {
                    if (!GetParam(httpMessage, "1", "index", out string index))
                    {
                        httpMessage.result = "command error! \nexample: getlastblock index";
                        return;
                    }
                    string height = await GetHeightAsync();

                    httpMessage.map["1"] = (long.Parse(height) - 19 * long.Parse(httpMessage.map["1"])) != 0 ? (long.Parse(height) - 19 * long.Parse(httpMessage.map["1"])).ToString() : "0";
                    HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                    httpMessage.result = result.result;
                } catch (Exception e)
                {
                    httpMessage.result = "command error! \nexample: getlastblock index";
                }
            }
            else if (httpMessage.map["0"] == "transfercount")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "search")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "miner")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "node")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "beruler")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "rules")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "stats")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "account")
            {
                HttpMessage result = await ComponentNetworkHttp.QueryCommand(Program.ruleIP + $"/{httpMessage.map["cmd"]}", httpMessage);

                httpMessage.result = result.result;
            }
            else if (httpMessage.map["0"] == "help")
            {
                OnHelp(httpMessage);
            }
            else
            {
                httpMessage.result = "command error";
            }
        }
示例#30
0
        public void Execute(DbSnapshot dbSnapshot, Transfer transfer, long height)
        {
            LuaVMCall    luaVMCall    = new LuaVMCall();
            LuaVMScript  luaVMScript  = null;
            LuaVMContext LuaVMContext = null;

            try
            {
                s_dbSnapshot = dbSnapshot;
                string address = (transfer.addressOut == null || transfer.addressOut == "") ? Wallet.ToAddress(CryptoHelper.Sha256(Encoding.UTF8.GetBytes(transfer.data))) : transfer.addressOut;
                LuaEnv luaenv  = GetLuaEnv(address);

                // rapidjson待优化,改为直接在C#层调用
                luaenv.Global.Set("contractAddress", address);
                luaenv.Global.Set("dbSnapshot", dbSnapshot);

                luaenv.DoString(initScript);

                if (transfer.addressOut == null || transfer.addressOut == "")
                {
                    // 当前版本只能由superAddress发布智能合约
                    if (consensus.superAddress != transfer.addressIn)
                    {
                        return;
                    }

                    luaVMScript = new LuaVMScript()
                    {
                        script = Base58.Decode(transfer.data)
                    };
                    LuaVMContext = new LuaVMContext()
                    {
                        jsonData = "{}".ToByteArray()
                    };
                    luaVMCall.fnName = "Create";
                    luaVMCall.args   = new FieldParam[0];
                    if (dbSnapshot.Contracts.Get(address) == null)
                    {
                        dbSnapshot.Contracts.Add(address, luaVMScript);
                    }
                    luaenv.DoString(luaVMScript.script);
                }
                else
                {
                    luaVMScript  = dbSnapshot.Contracts.Get(address);
                    LuaVMContext = dbSnapshot.Storages.Get(address);
                    luaVMCall    = LuaVMCall.Decode(transfer.data);
                    luaenv.DoString(luaVMScript.script, transfer.addressOut);
                    luaenv.DoString($"Storages = rapidjson.decode('{LuaVMContext.jsonData.ToStr()}')\n");
                }

                object[]    args   = luaVMCall.args.Select(a => a.GetValue()).ToArray();
                LuaFunction luaFun = luaenv.Global.Get <LuaFunction>(luaVMCall.fnName);

                luaenv.DoString($"curHeight    =  {height}\n");
                luaenv.DoString($"curAddress   = '{transfer.addressIn}'\n");
                luaFun.Call(args);

                // 待优化,改为直接在C#层调用
                luaenv.DoString("StoragesJson = rapidjson.encode(Storages)\n");
                LuaVMContext.jsonData = luaenv.Global.Get <string>("StoragesJson").ToByteArray();
                dbSnapshot.Storages.Add(address, LuaVMContext);
            }
            catch (Exception)
            {
                Log.Info($"LuaVMEnv.Execute Error, transfer.hash: {transfer.hash} , contract: {transfer.addressOut} func:{luaVMCall.fnName}");
            }
        }