Пример #1
0
        public void GenerateNewAccountFileFromPrivateKey(string pass, string path, string address, string key)
        {
            var service  = new KeyStoreService();
            var fileName = service.GenerateUTCFileName(address);

            using (var newfile = File.CreateText(Path.Combine(path, fileName)))
            {
                var newJson = service.EncryptAndGenerateDefaultKeyStoreAsJson(pass, HexByteConvertorExtensions.HexToByteArray(key), address);
                newfile.Write(newJson);
                newfile.Flush();
            }
        }
Пример #2
0
        public bool SubmitSolution(string digest, string fromAddress, string challenge, string difficulty, string target, string solution, Miner.IMiner sender)
        {
            lock (this)
            {
                if (IsChallengedSubmitted(challenge))
                {
                    OnStopSolvingCurrentChallenge(this, challenge);
                    Program.Print(string.Format("[INFO] Submission cancelled, nonce has been submitted for the current challenge."));
                    return(false);
                }
                m_challengeReceiveDateTime = DateTime.MinValue;

                var transactionID = string.Empty;
                var gasLimit      = new HexBigInteger(m_gasLimit);
                var userGas       = new HexBigInteger(UnitConversion.Convert.ToWei(new BigDecimal(m_gasToMine), UnitConversion.EthUnit.Gwei));

                var oSolution = new BigInteger(Utils.Numerics.HexStringToByte32Array(solution).ToArray());
                // Note: do not directly use -> new HexBigInteger(solution).Value
                //Because two's complement representation always interprets the highest-order bit of the last byte in the array
                //(the byte at position Array.Length - 1) as the sign bit,
                //the method returns a byte array with an extra element whose value is zero
                //to disambiguate positive values that could otherwise be interpreted as having their sign bits set.

                object[] dataInput = null;

                if (m_mintMethodInputParamCount > 1) // 0xBitcoin compatibility
                {
                    dataInput = new object[] { oSolution, HexByteConvertorExtensions.HexToByteArray(digest) }
                }
                ;

                else // Draft EIP-918 compatibility [2018-03-07]
                {
                    dataInput = new object[] { oSolution }
                };

                var retryCount          = 0u;
                var startSubmitDateTime = DateTime.Now;
                while (string.IsNullOrWhiteSpace(transactionID))
                {
                    try
                    {
                        var txCount = m_web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(fromAddress).Result;

                        var estimatedGasLimit = m_mintMethod.EstimateGasAsync(from: fromAddress,
                                                                              gas: gasLimit,
                                                                              value: new HexBigInteger(0),
                                                                              functionInput: dataInput).Result;

                        var transaction = m_mintMethod.CreateTransactionInput(from: fromAddress,
                                                                              gas: estimatedGasLimit,
                                                                              gasPrice: userGas,
                                                                              value: new HexBigInteger(0),
                                                                              functionInput: dataInput);

                        var encodedTx = Web3.OfflineTransactionSigner.SignTransaction(privateKey: m_account.PrivateKey,
                                                                                      to: m_contract.Address,
                                                                                      amount: 0,
                                                                                      nonce: txCount.Value,
                                                                                      gasPrice: userGas,
                                                                                      gasLimit: estimatedGasLimit,
                                                                                      data: transaction.Data);

                        if (!Web3.OfflineTransactionSigner.VerifyTransaction(encodedTx))
                        {
                            throw new Exception("Failed to verify transaction.");
                        }

                        transactionID = m_web3.Eth.Transactions.SendRawTransaction.SendRequestAsync("0x" + encodedTx).Result;

                        LastSubmitLatency = (int)((DateTime.Now - startSubmitDateTime).TotalMilliseconds);

                        if (!string.IsNullOrWhiteSpace(transactionID))
                        {
                            if (!IsChallengedSubmitted(challenge))
                            {
                                m_submittedChallengeList.Insert(0, challenge);
                                if (m_submittedChallengeList.Count > 100)
                                {
                                    m_submittedChallengeList.Remove(m_submittedChallengeList.Last());
                                }
                            }

                            Task.Factory.StartNew(() => GetTransactionReciept(transactionID, fromAddress, gasLimit, userGas, LastSubmitLatency));
                        }
                    }
                    catch (AggregateException ex)
                    {
                        var errorMessage = "[ERROR] " + ex.Message;

                        foreach (var iEx in ex.InnerExceptions)
                        {
                            errorMessage += "\n " + iEx.Message;
                        }

                        Program.Print(errorMessage);
                        if (IsChallengedSubmitted(challenge))
                        {
                            return(false);
                        }
                    }
                    catch (Exception ex)
                    {
                        var errorMessage = "[ERROR] " + ex.Message;

                        if (ex.InnerException != null)
                        {
                            errorMessage += "\n " + ex.InnerException.Message;
                        }

                        Program.Print(errorMessage);
                        if (IsChallengedSubmitted(challenge) || ex.Message == "Failed to verify transaction.")
                        {
                            return(false);
                        }
                    }

                    System.Threading.Thread.Sleep(1000);
                    if (string.IsNullOrWhiteSpace(transactionID))
                    {
                        retryCount++;
                    }

                    if (retryCount > 10)
                    {
                        Program.Print("[ERROR] Failed to submit solution for more than 10 times, please check settings.");
                        sender.StopMining();
                    }
                }
                if (m_submitDateTimeList.Count >= MAX_SUBMIT_DTM_COUNT)
                {
                    m_submitDateTimeList.RemoveAt(0);
                }
                m_submitDateTimeList.Add(DateTime.Now);

                return(true);
            }
        }
Пример #3
0
        public async Task PlayHand(long id, [FromBody] RespondToChallengeModel model)
        {
            var opponentId = new Guid(User.Claims.Single(cl => cl.Type == ClaimTypes.NameIdentifier).Value);

            var game = await _context.Games
                       .Include(x => x.Challenger)
                       .Include(x => x.Opponent)
                       .SingleAsync(x => x.Id == id && x.OpponentId == opponentId && x.OpponentHand == null);

            game.OpponentHand = model.HashedHand;
            await _context.SaveChangesAsync();

            var    assembly = typeof(GamesController).GetTypeInfo().Assembly;
            string abi      = null;
            string binary   = null;

            using (Stream resource = assembly.GetManifestResourceStream("api.BlindGame.json"))
            {
                using (var streamReader = new StreamReader(resource))
                {
                    var     contract = streamReader.ReadToEnd();
                    JObject obj      = JObject.Parse(contract);
                    abi    = obj.Property("abi").Value.ToString();
                    binary = obj.Property("unlinked_binary").Value.ToString();
                }
            }

            var web3 = new Web3(_account.Value.Address);

            web3.TransactionManager = new AccountSignerTransactionManager(web3.Client, _account.Value.MasterAccountPrivateKey);
            var deployedContractResult = await web3.Eth.DeployContract.SendRequestAsync(abi, binary, _account.Value.MasterAccountAddress, new HexBigInteger(900000),
                                                                                        game.Challenger.Address, game.Opponent.Address, HexByteConvertorExtensions.HexToByteArray(game.ChallengerHand), HexByteConvertorExtensions.HexToByteArray(game.OpponentHand));

            var receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(deployedContractResult);

            while (receipt == null)
            {
                Thread.Sleep(5000);
                receipt = await web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(deployedContractResult);
            }
            var contractAddress = receipt.ContractAddress;

            game.Address = contractAddress;
            await _context.SaveChangesAsync();
        }