Exemple #1
0
 public async Task <String> SendRequestAsync(HexString valueToConvertHex, string id = Constants.DEFAULT_REQUEST_ID)
 {
     return(await base.SendRequestAsync(id, valueToConvertHex));
 }
Exemple #2
0
 public static PublicKey FromHex(String s)
 {
     return(new PublicKey(HexString.ToByteArray(s)));
 }
        public IActionResult GetDeviceTokenRestore([FromForm] string guid, [FromForm] string deviceName, [FromForm] string secret, [FromForm]  string challenge, [FromForm] string signaturecold)
        {
            dynamic ret          = new System.Dynamic.ExpandoObject();
            string  errorMessage = "";
            bool    isError      = false;

            if (Helper.IsSecretValid(guid, secret, _connstrWallet, _csprng))
            {
                if (signaturecold == "")
                {
                    isError = true;
                }

                if (!isError)
                {
                    //get the users public hot and cold key
                    //verify the signature on the message

                    //if both signatures match then reset 2fa

                    //get hot and cold public keys from the database

                    NpgsqlConnection conn = new NpgsqlConnection(_connstrWallet);

                    string userHotKey  = "";
                    string userColdKey = "";

                    //validate that the address handed to us is valid
                    conn.Open();
                    try
                    {
                        NpgsqlCommand cmd = new NpgsqlCommand("sp_pubKeyByAccount", conn);
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add(new NpgsqlParameter("p_guid", guid));
                        NpgsqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
                        if (reader.HasRows)
                        {
                            reader.Read();

                            if (reader.IsDBNull(0))
                            {
                                isError      = true;
                                errorMessage = "ErrInvalid";
                            }
                            else
                            {
                                userHotKey  = reader.GetString(0);
                                userColdKey = reader.GetString(1);
                            }
                        }
                        else
                        {
                            isError      = true;
                            errorMessage = "ErrAccount";
                        }
                        reader.Dispose();
                    }
                    catch (Exception ex)
                    {
                        isError      = true;
                        errorMessage = "ErrInvalid";
                    }
                    finally
                    {
                        conn.Close();
                    }

                    userColdKey = Helper.Decrypt(userColdKey, _csprng);

                    BIP32  bipCold = new BIP32(userColdKey, _csprng.Getsecp256k1());
                    string mcold   = HexString.FromByteArray(bipCold.eckey.pubKey);

                    bool coldvalid = bipCold.eckey.verifySignature(HexString.ToByteArray(challenge), HexString.ToByteArray(signaturecold));


                    if (coldvalid)
                    {
                        //sp_resetTwoFactor
                        //reset 2 factor
                        //always generate new tokens here
                        //so every pair request generates a new set
                        //of tokens that invalidate the previous set

                        byte[] devkey = new byte[32];

                        _csprng.getRandomValues(devkey);

                        string deviceKey = HexString.FromByteArray(devkey);

                        string enckey = Helper.Encrypt(deviceKey, _csprng);


                        //two factor token
                        byte[] tft = new byte[32];

                        _csprng.getRandomValues(tft);

                        string deviceToken = HexString.FromByteArray(tft);


                        byte[] bregToken = new byte[32];

                        _csprng.getRandomValues(bregToken);

                        string regToken = HexString.FromByteArray(bregToken);


                        conn = new NpgsqlConnection(_connstrWallet);

                        conn.Open();
                        try
                        {
                            DateTime expiry = DateTime.Now.AddYears(20);

                            NpgsqlCommand cmd = new NpgsqlCommand("sp_createemailtoken", conn);
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add(new NpgsqlParameter("p_emailvalidationtoken", deviceToken));
                            cmd.Parameters.Add(new NpgsqlParameter("p_walletid", guid));
                            cmd.Parameters.Add(new NpgsqlParameter("p_emailaddress", ""));
                            cmd.Parameters.Add(new NpgsqlParameter("p_expirydate", expiry));
                            int tmpisused = 0;
                            cmd.Parameters.Add(new NpgsqlParameter("p_isused", tmpisused));
                            cmd.Parameters.Add(new NpgsqlParameter("p_tokentype", 3));
                            cmd.ExecuteNonQuery();


                            cmd             = new NpgsqlCommand("sp_updatedevicetoken", conn);
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add(new NpgsqlParameter("p_guid", guid));
                            cmd.Parameters.Add(new NpgsqlParameter("p_devicename", deviceName));
                            cmd.Parameters.Add(new NpgsqlParameter("p_devicekey", enckey));
                            cmd.Parameters.Add(new NpgsqlParameter("p_twofactortoken", deviceToken));
                            cmd.Parameters.Add(new NpgsqlParameter("p_regtoken", regToken));
                            cmd.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            isError      = true;
                            errorMessage = "ErrInvalid";
                        }
                        finally
                        {
                            conn.Close();
                        }

                        //deviceKey = Decrypt(deviceKey);



                        ret.DeviceToken = deviceToken;
                        ret.DeviceKey   = deviceKey;
                        ret.RegToken    = regToken;
                    }
                    else
                    {
                        isError      = true;
                        errorMessage = "ErrInvalidSignature";
                    }
                }
            }
            else
            {
                isError      = true;
                errorMessage = "ErrInvalid";
            }


            if (isError)
            {
                return(Json(new ErrorObject(errorMessage)));
            }
            else
            {
                return(Json(ret));
            }
        }
 public RpcRequest BuildRequest(HexString valueToConvert, object id = null)
 {
     return(base.BuildRequest(id, valueToConvert));
 }
Exemple #5
0
 public abstract PINPadResponse <string> SetTPK(HexString tpk);
Exemple #6
0
 private string GetDebugInfo()
 {
     return("Index=" + Index + " Id=" + HexString.GetString(_link.GetHashCode()) + " Value=" + (_link.Value ?? "{null}"));
 }
Exemple #7
0
 /// <summary>
 /// Read Sector with KEY_B
 /// </summary>
 private void BtnReadSectorB_Click(object sender, EventArgs e)
 {
     this.TraceMsg.Trace("Read Card by KeyB..." + this.KeyB.Text.Trim(), true);
     byte[] keyB = HexString.FromHexString(this.KeyB.Text.Trim(), "-");
     ReadSector(M1KeyMode.KEY_B, keyB);
 }
Exemple #8
0
        private void txtTx_TextChanged(object sender, EventArgs e)
        {
            if (disableUpdate)
            {
                return;
            }

            try
            {
                Transaction tx = new Transaction(HexString.ToByteArray(txtTx.Text));

                // Disable *_Changed events
                disableUpdate = true;

                // Clear everything
                UTXO.Clear();
                updateUTXOList();
                selectedUTXO.Clear();
                dgvOutputs.Rows.Clear();
                outputs.Clear();

                foreach (TxIn txin in tx.inputs)
                {
                    TxOutId txi;
                    TxOut   txo;

                    // Try local bitcoind first
                    if (rpc != null)
                    {
                        try
                        {
                            string      sPrevTx = rpc.doRequest <string>("getrawtransaction", new object[] { HexString.FromByteArrayReversed(txin.prevOut) });
                            Transaction prevTx  = new Transaction(HexString.ToByteArray(sPrevTx));
                            txi = new TxOutId(txin.prevOut, txin.prevOutIndex);
                            txo = prevTx.outputs[txin.prevOutIndex];
                            UTXO.Add(txi, txo);
                            selectedUTXO.Add(txi, txo);
                            continue;
                        }
                        catch (Exception)
                        {
                        }
                    }

                    // Get from blockchain if bitcoind fails
                    try
                    {
                        string json;
                        using (WebClient wc = new WebClient())
                        {
                            json = wc.DownloadString("https://blockchain.info/rawtx/" + HexString.FromByteArrayReversed(txin.prevOut));
                        }
                        JavaScriptSerializer          jss  = new JavaScriptSerializer();
                        Dictionary <string, object>   jso  = jss.Deserialize <Dictionary <string, object> >(json);
                        Dictionary <string, object>[] outs = jss.ConvertToType <Dictionary <string, object>[]>(jso["out"]);
                        Address addr         = new Address((string)outs[txin.prevOutIndex]["addr"]);
                        byte[]  scriptPubKey = scriptPubKey = ScriptTemplate.PayToAddress(addr).ToBytes();
                        txi = new TxOutId(txin.prevOut, txin.prevOutIndex);
                        txo = new TxOut(jss.ConvertToType <UInt64>(outs[txin.prevOutIndex]["value"]), scriptPubKey);
                        UTXO.Add(txi, txo);
                        selectedUTXO.Add(txi, txo);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Could not get input data.");
                        return;
                    }
                }
                updateUTXOList();
                foreach (DataGridViewRow row in dgvInputs.Rows)
                {
                    row.Cells["inSelected"].Value = true;
                }
                foreach (TxOut txout in tx.outputs)
                {
                    string addr;
                    try
                    {
                        addr = Address.FromScript(txout.scriptPubKey).ToString();
                    }
                    catch (Exception)
                    {
                        addr = "Could not decode address";
                    }
                    dgvOutputs.Rows.Add(addr, (decimal)txout.value / 100000000m);
                    outputs.Add(txout);
                }
                updateTx(false);
                txtTx.ForeColor = SystemColors.WindowText;
            }
            // Transaction invalid
            catch (Exception)
            {
                txtTx.ForeColor = Color.Red;
                return;
            }
            finally
            {
                disableUpdate = false;
            }
        }
Exemple #9
0
        private void btnFromBitcoind_Click(object sender, EventArgs e)
        {
            if (!getRpc())
            {
                return;
            }

            try
            {
                object[] obj = rpc.doRequest <object[]>("listunspent", new object[0]);

                for (int i = 0; i < obj.Length; i++)
                {
                    Dictionary <string, object> p = rpc.jss.ConvertToType <Dictionary <string, object> >(obj[i]);

                    string txid         = (string)p["txid"];
                    int    vout         = (int)p["vout"];
                    ulong  amount       = (ulong)(((decimal)p["amount"]) * 100000000m);
                    string scriptPubKey = (string)p["scriptPubKey"];

                    UTXO.Add(new TxOutId(HexString.ToByteArrayReversed(txid), (uint)vout), new TxOut(amount, HexString.ToByteArray(scriptPubKey)));
                }

                updateUTXOList();
            }
            catch (Exception)
            {
                MessageBox.Show("Error downloading unspent outputs.");
                return;
            }
        }
 public void TestOddLengthString()
 {
     var hexString = new HexString("a");
 }
Exemple #11
0
        private void btnFromBlockchain_Click(object sender, EventArgs e)
        {
            try
            {
                WebClient            wc   = new WebClient();
                string               json = wc.DownloadString("http://blockchain.info/unspent?active=" + txtAddress.Text);
                JavaScriptSerializer jss  = new JavaScriptSerializer();

                Dictionary <string, object>   jso     = jss.Deserialize <Dictionary <string, object> >(json);
                Dictionary <string, object>[] outputs = jss.ConvertToType <Dictionary <string, object>[]>(jso["unspent_outputs"]);
                foreach (Dictionary <string, object> txo in outputs)
                {
                    string tx_hash     = (string)txo["tx_hash"];
                    int    tx_output_n = (int)txo["tx_output_n"];
                    ulong  value       = Convert.ToUInt64((string)txo["value_hex"], 16);
                    string script      = (string)txo["script"];

                    UTXO.Add(new TxOutId(HexString.ToByteArray(tx_hash), (uint)tx_output_n), new TxOut(value, HexString.ToByteArray(script)));
                }
                updateUTXOList();
            }
            catch (Exception)
            {
                MessageBox.Show("Error downloading unspent outputs.");
                return;
            }
        }
 public void TestNullString()
 {
     var hexString = new HexString((string)null);
 }
Exemple #13
0
 private string GetDebugInfo()
 {
     return("Id=" + HexString.GetString(GetHashCode()) + " Value=" + (Value ?? "{null}"));
 }
Exemple #14
0
 public RpcRequest BuildRequest(HexString valueToConvert, string id = Constants.DEFAULT_REQUEST_ID)
 {
     return(base.BuildRequest(id, valueToConvert));
 }
Exemple #15
0
 public void InvalidFormatSpecifier()
 {
     Assert.Throws <FormatException>(() => HexString.Encode(new byte[0], "..."));
 }
Exemple #16
0
        static void Main(string[] args)
        {
            //
            MemberInfo[] members = typeof(Test2).GetPropertiesAndFields().ToArray();

            //
            string json = JsonConvert.SerializeObject(new Test1
            {
                Md5 = "test".MD5(Encoding.UTF8),
                Msg = Guid.Empty.ToBase64()
            });

            Test1 test1 = JsonConvert.DeserializeObject <Test1>(json);

            Assert.IsTrue(test1.Md5 == "test".MD5(Encoding.UTF8));
            Assert.IsTrue(test1.Msg == Guid.Empty.ToBase64());

            //
            Uri uri = new Uri("https://item.jd.com/37175085087.html");

            Assert.IsTrue(uri.GetExtension() == ".html");

            //
            uri = new Uri("https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1");

            Assert.IsTrue(uri.SchemaAndHost() == "https://www.baidu.com");

            Assert.IsTrue(uri.GetUri("/test/test.html").OriginalString == "https://www.baidu.com/test/test.html");

            Assert.IsTrue(uri.IsInternalLink(uri.GetUri("/test/test.html")));

            Assert.IsFalse(uri.IsInternalLink(new Uri("https://cn.bing.com/")));

            //
            Kernel32.AddConsoleCtrlHandler(() =>
            {
                //
            });

            //
            RegEdit.UpdateWebBrowserVersion();

            //
            {
                Asyn.Exec(() =>
                {
                    Tcp.Listen("127.0.0.1", 10601, (stream) =>
                    {
                        string request = stream.ReadLine(Encoding.UTF8);

                        Console.WriteLine("request:" + request);

                        stream.Write(request.ToByteArray(Encoding.UTF8));
                    });
                });
            }

            {
                string response = Tcp.SendLine("127.0.0.1", 10601, "test", Encoding.UTF8);

                Console.WriteLine("response:" + response);

                response = Tcp.SendLine("127.0.0.1", 10601, "test", Encoding.UTF8);

                Console.WriteLine("response:" + response);
            }

            //
            Asyn.Exec(() =>
            {
                NamedPipe.Server("testPipe", (stream) =>
                {
                    string request = stream.ReadLine(Encoding.UTF8);

                    Console.WriteLine("request:" + request);

                    stream.WriteLine(request, Encoding.UTF8);
                });
            });

            {
                string response = NamedPipe.SendLine("testPipe", "hello", Encoding.UTF8);

                Console.WriteLine("response:" + response);

                response = NamedPipe.SendLine("testPipe", "hello", Encoding.UTF8);

                Console.WriteLine("response:" + response);
            }

            //
            Cmd.Exec("ping bibaoke.com");

            //
            Cmd.Exec("TestForm1.exe");

            //
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://265.com");

                using (WebResponse response = request.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        byte[] data1 = stream.ToByteArray();

                        string text1 = data1.ToString(Encoding.UTF8);

                        WebClient client = new WebClient();

                        byte[] data2 = client.DownloadData("http://265.com");

                        string text2 = data2.ToString(Encoding.UTF8);

                        Assert.IsTrue(data1.Length == data2.Length);
                    }
                }
            }

            //
            string testString = "test string";

            string file = Application.SetupDir.CombinePath(Guid.NewGuid());

            file.Write(testString, Encoding.UTF8);

            Assert.IsTrue(file.ReadString(Encoding.UTF8) == testString);

            file.DeleteFile();

            //
            Pool pool = new Pool(50);

            for (int i = 0; i < 100; i++)
            {
                pool.Execute(i, j => Console.WriteLine(j));
            }

            pool.Execute(() => Thread.Sleep(1000));

            pool.Wait();

            //
            int number1 = "10".ToInt();

            string number2String = null;

            int?number2 = number2String.ToInt();

            Assert.IsTrue(number1 == 10);

            Assert.IsTrue(number2 == null);

            //
            byte[] data = "测试字符串".ToByteArray(Encoding.UTF8);

            Base64 base64 = new Base64(data);

            HexString hex = new HexString(data);

            Assert.IsTrue(base64.ToHexString() == hex.ToString());

            Assert.IsTrue(base64 == hex.ToBase64());

            //
            Assert.IsTrue(new Uri("http://bibaoke.com/post/74").GetUri("71") == new Uri("http://bibaoke.com/post/71"));

            Assert.IsTrue(new Uri("http://bibaoke.com/post/74").GetUri("/post/71") == new Uri("http://bibaoke.com/post/71"));

            Assert.IsTrue(new Uri("http://bibaoke.com").GetUri("post/71") == new Uri("http://bibaoke.com/post/71"));

            //
            Assert.IsTrue(new Uri("http://bibaoke.com/icon").SetQuery("char=和") == new Uri("http://bibaoke.com/icon?char=和"));

            Assert.IsTrue(
                new Uri("http://bibaoke.com/icon?char=和").SetQuery("color=white") == new Uri("http://bibaoke.com/icon?char=和&color=white"));

            //
            Assert.IsTrue(new Uri("http://jianzhimao.com.com").GetDomain() == "com.com");

            Assert.IsTrue(new Uri("http://pconline.com.cn").GetDomain() == "pconline.com.cn");

            //
            Assert.IsTrue(2.Pow(3) == 8);

            //
            Assert.IsTrue("نیک تم | قالب وردپرس, قالب اورجينال فارسي و قالب وردپرس شرکتی".HasUnicode());

            //
            Encoding gbk = MyEncoding.GBK;

            //
            Assert.IsTrue("".SplitByWhiteSpace().Length == 0);

            Assert.IsTrue(" ".SplitByWhiteSpace().Length == 0);

            Assert.IsTrue(" test1  test2 ".SplitByWhiteSpace()[1] == "test2");

            //
            Assert.IsTrue(new int[] { 1, 2 }.ExtArray(new int[0]).Length == 2);

            //
            Assert.IsTrue("test".Repeat(2) == "testtest");

            //
            int[] testArray = new int[100];

            100.Each(index => testArray[index] = index);

            IEnumerable <int> enumerator = testArray.GetEnumerator(50);

            int count = 0;

            enumerator.Each((index, item) =>
            {
                Assert.IsTrue(item == index + 50);

                count++;
            });

            Assert.IsTrue(count == 50);

            //
            Assert.IsTrue("abcd".SubstringUnsafe(1, 2) == "bc");

            Assert.IsTrue("".SubstringUnsafe(0) == "");

            //
            file = Application.SetupDir.CombinePath("testReadBytes.txt");

            Assert.IsTrue(file.ReadString(Encoding.UTF8, true) == "abc");

            file.Write("abcd", Encoding.UTF8);

            Assert.IsTrue(file.ReadString(Encoding.UTF8, true) == "abcd");

            //
            Regex pattern = @"(?<order>order\s+by\s+.*?)\s*$".ToRegex(
                RegexOptions.Compiled |
                RegexOptions.ExplicitCapture |
                RegexOptions.IgnoreCase);

            Assert.IsTrue(
                pattern.Match("select * from user order by dept desc, id asc").GetValue("order") == "order by dept desc, id asc");

            Assert.IsTrue(
                pattern.Match("select * from user order by id ").GetValue("order") == "order by id");

            //
            Assert.IsTrue("90".IsInt());
            Assert.IsTrue("-90".IsInt());
            Assert.IsTrue("0".IsInt());
            Assert.IsTrue("-9".IsInt());
            Assert.IsTrue("-19".IsInt());
            Assert.IsTrue("09".IsInt());
            Assert.IsTrue("9".IsInt());
            Assert.IsFalse("1.9".IsInt());
            Assert.IsTrue(" 19".IsInt());
            Assert.IsTrue("19".IsInt());
            Assert.IsTrue("19 ".IsInt());
            Assert.IsFalse("1九".IsInt());

            //
            Assert.IsTrue("192.168.1.1".IsIpv4());
            Assert.IsFalse("192.168.1".IsIpv4());

            //
            Agent agent = new Agent("ping vaiying.com -t", AgentMode.Restart, TimeSpan.FromSeconds(2));

            agent.StartUp();

            Thread.Sleep(3000);

            agent.ShutDown();

            //
            DateTime startTime = DateTime.Now.AddSeconds(2);

            Agent notepad = new Agent("notepad", AgentMode.Singleton, startTime.Hour, startTime.Minute, startTime.Second);

            notepad.StartUp();

            Thread.Sleep(1000);

            notepad.ShutDown();

            //
            long l = 10;

            Assert.IsTrue(l.ToInt() == 10);

            l = int.MinValue;

            Assert.IsTrue(l.ToInt() == int.MinValue);

            //
            Syn.Wait(() =>
            {
                100.Each((index) =>
                {
                    Console.WriteLine(index);

                    Thread.Sleep(10);
                });

                return(true);
            });

            //
            try
            {
                Syn.Wait(TimeSpan.FromSeconds(1), () =>
                {
                    return(false);
                });
            }
            catch (TimeoutException ex)
            {
                Console.WriteLine(ex.Message);
            }

            //
            Process.GetCurrentProcess().Kill();
        }
Exemple #17
0
 public void InvalidHexStrings()
 {
     Assert.Throws <InvalidDataException>(() => HexString.Decode("0"));
     Assert.Throws <InvalidDataException>(() => HexString.Decode("0Z"));
 }
Exemple #18
0
 public static PrivateKey FromHex(String s, Boolean compress = false)
 {
     return(new PrivateKey(HexString.ToByteArray(s), compress));
 }
Exemple #19
0
 /// <summary>
 /// Read Sector with KEY_A
 /// </summary>
 private void BtnReadSectorA_Click(object sender, EventArgs e)
 {
     this.TraceMsg.Trace("Read Card Sector With Key_A ..." + this.KeyA.Text.Trim(), true);
     byte[] keyA = HexString.FromHexString(this.KeyA.Text.Trim(), "-");
     ReadSector(M1KeyMode.KEY_A, keyA);
 }
Exemple #20
0
        static void _Main(string[] args)
        {
            TcpClient     tcpClient = new TcpClient("10.1.1.10", 8333);
            NetworkStream ns        = tcpClient.GetStream();

            NetAddr localaddr = new NetAddr(Services.NODE_NETWORK,
                                            ((IPEndPoint)tcpClient.Client.LocalEndPoint).Address, (UInt16)((IPEndPoint)tcpClient.Client.LocalEndPoint).Port);
            NetAddr remaddr = new NetAddr(Services.NODE_NETWORK,
                                          ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address, (UInt16)((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port);

            new Message("version", Version.Default(remaddr, localaddr, 0)).Write(ns);

            List <InvVect> lst = new List <InvVect>();
            StreamReader   fs  = new StreamReader(new FileStream(@"C:\inv.txt", FileMode.Open));
            string         line;

            while ((line = fs.ReadLine()) != null)
            {
                lst.Add(new InvVect(InvType.MSG_TX, HexString.ToByteArray(line)));
            }
            Inv iv = new Inv(lst.ToArray());

            Message mtx = new Message("inv", iv);

            //Tx tx = new Tx(HexString.ToByteArray("0100000001b924de36d37e9b46171036c2380dd3f86c33de7868b95f295c79d057abb876c9000000006c493046022100d35d290d515b2310a81850b14522f3965982ad059b08b7d6646372c9f6f98642022100d2d0fa06f8afa2a9df7bf7e06f901f08fc40882f486b292c217c96706912f23a012103b5091600a12d971b056170a682ea596b6680dd8a784f2960b1bfdc891155db44ffffffff0100ae4c2d000000001976a91443e86640aa84e2a53597e79109e912f8f9ebda1188ac00000000"));

            //Message mtx = new Message("tx", tx);

            mtx.Write(ns);

            while (tcpClient.Client.Connected)
            {
                Message    msg = Message.FromStream(ns);
                ISerialize p   = msg.payload;
                Console.WriteLine(msg.payload);
                switch (msg.strcmd)
                {
                case "addr":
                    break;

                case "alert":
                    break;

                case "block":
                    break;

                case "getaddr":
                {
                    //	Message m = new Message("addr", new Addr());
                    break;
                }

                case "getblocks":
                    break;

                case "getdata":
                    break;

                case "getheaders":
                    break;

                case "headers":
                    break;

                case "inv":
                {
                    Inv inv = (Inv)msg.payload;
                    new Message("getdata", new GetData(inv.inventory)).Write(ns);
                    break;
                }

                case "ping":
                    break;

                case "tx":
                    break;

                case "verack":
                    break;

                case "version":
                {
                    Message m = new Message("verack", new VerAck());
                    m.Write(ns);
                    break;
                }

                default:
                    break;
                }
            }

            /*
             * string line;
             *
             * Transaction txUnspent = new Transaction(HexString.ToByteArray("0100000001f165b1179cb8ed7057540375884214287cf1592f2325080364f0bd8ef51d638b010000006a47304402207cf76bb48434e70ff0ea86a949ec4191fff0c31fdbbf6441c28293a09cb6841d022039906ff8b98761aa0d113e975c7af277d091a3cb9aaceae07dffe91f13fd65830121031adaac125ad58a48d1289bd44624d569b3ace8f9c59e02557e8ad00787dc7e06ffffffff0100ae4c2d00000000232102004066b81e658b2535b951c309edc4807a5260d9f1387e5dfda2d91355e562efac00000000"));
             *
             * Address addr = new Address("1QJqE3KiyFBSCP12kTybW1ZRSeuJZTUwBY");
             *
             * TxIn txIn = new TxIn(txUnspent.hash, 0, new Byte[0]);
             * TxOut txOut = new TxOut(760000000, ScriptTemplate.PayToAddress(addr).ToBytes());
             *
             * Transaction tx = new Transaction(1, new TxIn[] { txIn }, new TxOut[] { txOut }, 0);
             *
             * PrivateKey pk = PrivateKey.FromWIF("L1F95LNfoyGozceafTC1Pex8296YeF3EbsfETs22E83uhqVF5PBy");
             *
             * tx.inputs[0].Sign(tx, txUnspent.outputs[0], pk);
             *
             * Console.WriteLine(HexString.FromByteArray(tx.ToBytes()));
             *
             * Script t = new Script(tx.inputs[0].scriptSig, txUnspent.outputs[0].scriptPubKey);
             * Console.WriteLine(t.Evaluate(tx, 0));
             *
             * /****/
            /*
             * int blockFileNum = 0;
             *
             * FileStream fs = new FileStream(@"C:\Users\Administrator\AppData\Roaming\Bitcoin\blocks\blk" + blockFileNum.ToString("D5") + ".dat", FileMode.Open);
             * List<Block_Disk> blocks = new List<Block_Disk>();
             * List<Byte[]> blockHashes = new List<byte[]>();
             * List<Address> addrs = new List<Address>();
             * while (fs.Position < fs.Length)
             * {
             *  Block_Disk b;
             *  b = Block_Disk.FromStream(fs);
             *  if (b.blockSize == 0)
             *  {
             *      blockFileNum++;
             *      try
             *      {
             *          fs = new FileStream(@"C:\Users\Administrator\AppData\Roaming\Bitcoin\blocks\blk" + blockFileNum.ToString("D5") + ".dat", FileMode.Open);
             *      }
             *      catch (FileNotFoundException)
             *      {
             *          break;
             *      }
             *      continue;
             *  }
             *  foreach (Transaction t in b.txns)
             *      foreach (TxOut txo in t.outputs)
             *      {
             *          addrs.Add(Address.FromScript(txo.script));
             *          //Console.WriteLine(Address.FromScript(txo.script));
             *          //Console.ReadLine();
             *      }
             *  //blockHashes.Add(b.prev_block);
             *  //Console.WriteLine(HexString.FromByteArray(b.hash));
             *  //blocks.Add(b);
             * }
             * Console.WriteLine(HexString.FromByteArray(blockHashes[blockHashes.Count() - 1]));
             * /**/
            Console.ReadLine();
        }
Exemple #21
0
 public async Task <string> SendRequestAsync(HexString valueToConvertHex, object id = null)
 {
     return(await base.SendRequestAsync(id, valueToConvertHex).ConfigureAwait(false));
 }
Exemple #22
0
 public string ToHexString() => HexString.FromBytes(Data);
Exemple #23
0
 public readonly string ToHexString() => HexString.FromBytes(Data);
Exemple #24
0
        public static void Main(string[] args)
        {
            BlockQueue q = new BlockQueue();

            FileStream fso = new FileStream(@"D:\bootstrap.dat", FileMode.Create);

            Dictionary <Hash, int>       diskBlockIndex = new Dictionary <Hash, int>();
            Dictionary <int, Block_Disk> diskBlocks     = new Dictionary <int, Block_Disk>();

            List <Queue <Hash> > chains = new List <Queue <Hash> >();

            chains.Add(new Queue <Hash>());

            Queue <Hash> bestChain = new Queue <Hash>();

            bool first = true;

            int index = 0;

            while (q.Count > 0)
            {
                Block_Disk b = q.Dequeue();
//				diskBlocks.Add(index, b);
                diskBlockIndex.Add(b.Hash, index);

                if (first)
                {
                    chains.Single().Enqueue(b.Hash);
                    first = false;
                }
                else
                {
                    int ci = chains.FindIndex(x => x.ToList().Contains(b.prev_block));
                    if (ci < 0)
                    {
                        Console.WriteLine(HexString.FromByteArrayReversed(b.Hash));
                        Console.WriteLine(HexString.FromByteArrayReversed(b.prev_block));
                        Console.WriteLine(HexString.FromByteArrayReversed(chains[ci].Last()));
                        throw new Exception("Invalid PrevBlock!");
                    }
                    if (chains[ci].Last().Equals(b.prev_block))
                    {
                        // Add to chain
                        chains[ci].Enqueue(b.Hash);
                    }
                    else
                    {
                        // not last block in chain, duplicate and add
                        List <Hash> l  = chains[ci].ToList();
                        int         bi = l.FindIndex(x => x.Equals(b.prev_block));
                        l.RemoveRange(bi + 1, l.Count - (bi + 1));
                        l.Add(b.Hash);
                        chains.Add(makeQueue(l));
                    }

                    int longestChain = chains.Max(x => x.Count);
                    chains.RemoveAll(x => x.Count < (longestChain - MAX_ORPHAN_DEPTH));

                    while (chains.Max(x => x.Count) > MAX_ORPHAN_DEPTH * 2)
                    {
                        bestChain.Enqueue(chains.First(x => x.Count == chains.Max(y => y.Count)).Peek());
                        chains.ForEach(c => c.Dequeue());
                        chains.RemoveAll(c => c.Count == 0);
                    }
                }
                index++;
            }
            while (chains.Count > 0 && chains.Max(x => x.Count) > 0)
            {
                bestChain.Enqueue(chains.First(x => x.Count == chains.Max(y => y.Count)).Peek());
                chains.ForEach(c => c.Dequeue());
                chains.RemoveAll(c => c.Count == 0);
            }

            Console.ReadLine();
        }
        public void Mining()
        {
            var(privateKey, publicKey) = SignManager.GenerateKeys();
            var publickKeyHash = new HexString(HashUtil.RIPEMD_SHA256(publicKey));
            //Genesis Mining
            var genesis = BlockchainManager.CreateGenesis();
            var miner   = new Miner
            {
                MinerKeyHash = publickKeyHash
            };

            Console.WriteLine("Mining");
            miner.Mining(genesis, Context.CancellationToken);
            BlockchainManager.Chain.Add(genesis);


            for (var i = 0; i < 10; i++)
            {
                var gg = BlockchainManager.CreateCoinBaseTransaction(i + 1, publickKeyHash.Bytes, $"まかろに{i}");
                gg.TimeStamp = DateTime.UtcNow;
                var txs = new List <Transaction>()
                {
                    gg
                };
                var rootHash = HashUtil.ComputeMerkleRootHash(txs.Select(x => x.Id).ToList());

                var b = new Block()
                {
                    PreviousBlockHash = BlockchainManager.Chain.Last().Id,
                    Transactions      = txs,
                    MerkleRootHash    = rootHash,
                    Timestamp         = DateTime.UtcNow,
                    Bits = 1
                };
                miner.Mining(b, Context.CancellationToken);
                BlockchainManager.Chain.Add(b);
                Task.Delay(10).GetAwaiter().GetResult();
            }

            //Second Block Mining
            Console.WriteLine($"{genesis.Transactions.Count}");
            var tb  = new TransactionBuilder();
            var ttx = BlockchainManager.Chain.SelectMany(x => x.Transactions).First(x => x.Engraving == "まかろに0");

            var input = new Input()
            {
                TransactionId = ttx.Id,
                OutputIndex   = 0,
            };
            var output = new Output()
            {
                Amount        = 10,
                PublicKeyHash = publickKeyHash.Bytes
            };

            tb.Inputs.Add(input);
            tb.Outputs.Add(output);
            var tx = tb.ToSignedTransaction(privateKey, publicKey);

            BlockchainManager.TransactionPool.Add(tx);
            miner.Start();

            Console.WriteLine($"{BlockchainManager.VerifyBlockchain()} : OK");
            Console.ReadLine();
        }
Exemple #26
0
 public void WriteHexString(TextWriter output)
 {
     HexString.WriteHexStringTo(output, Data);
 }
        public IActionResult GetDeviceToken([FromForm] string guid, [FromForm] string sharedid, [FromForm] string deviceName)
        {
            if (!Helper.IsCallerValid(guid, sharedid, _connstrWallet))
            {
                ErrorObject ro = new ErrorObject();
                ro.message = "Invalid";
                ro.error   = true;
                return(Json(ro));
            }

            //sp_getDevice
            string errorMessage = "";
            bool   isError      = false;

            //always generate new tokens here
            //so every pair request generates a new set
            //of tokens that invalidate the previous set

            byte[] devkey = new byte[32];

            _csprng.getRandomValues(devkey);

            string deviceKey = HexString.FromByteArray(devkey);

            string enckey = Helper.Encrypt(deviceKey, _csprng);


            //two factor token
            byte[] tft = new byte[32];

            _csprng.getRandomValues(tft);

            string deviceToken = HexString.FromByteArray(tft);


            byte[] bregToken = new byte[32];

            _csprng.getRandomValues(bregToken);

            string regToken = HexString.FromByteArray(bregToken);


            NpgsqlConnection conn = new NpgsqlConnection(_connstrWallet);

            conn.Open();
            try
            {
                DateTime expiry = DateTime.Now.AddYears(20);

                NpgsqlCommand cmd = new NpgsqlCommand("sp_createemailtoken", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new NpgsqlParameter("p_emailvalidationtoken", deviceToken));
                cmd.Parameters.Add(new NpgsqlParameter("p_walletid", guid));
                cmd.Parameters.Add(new NpgsqlParameter("p_emailaddress", ""));
                cmd.Parameters.Add(new NpgsqlParameter("p_expirydate", expiry));
                int tmpused = 0;
                cmd.Parameters.Add(new NpgsqlParameter("p_isused", tmpused));
                cmd.Parameters.Add(new NpgsqlParameter("p_tokentype", 3));
                cmd.ExecuteNonQuery();


                cmd             = new NpgsqlCommand("sp_updatedevicetoken", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new NpgsqlParameter("p_guid", guid));
                cmd.Parameters.Add(new NpgsqlParameter("p_devicename", deviceName));
                cmd.Parameters.Add(new NpgsqlParameter("p_devicekey", enckey));
                cmd.Parameters.Add(new NpgsqlParameter("p_twofactortoken", deviceToken));
                cmd.Parameters.Add(new NpgsqlParameter("p_regtoken", regToken));
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                isError      = true;
                errorMessage = "ErrInvalid";
            }
            finally
            {
                conn.Close();
            }

            //deviceKey = Decrypt(deviceKey);

            if (isError)
            {
                return(Json(new ErrorObject(errorMessage)));
            }
            else
            {
                dynamic ret = new System.Dynamic.ExpandoObject();
                ret.DeviceToken = deviceToken;
                ret.DeviceKey   = deviceKey;
                ret.RegToken    = regToken;
                return(Json(ret));
            }
        }
 public void VerifySignature(string hash, string signature, string publickey, bool pass)
 {
     Assert.Equal(pass, Sha1.VerifySignature(HexString.ToByteArray(hash), Convert.FromBase64String(signature), publickey));
 }
        public IActionResult GetDevMigTwoFactorToken([FromForm] string guid, [FromForm]  string sharedid, [FromForm] string twoFactorToken)
        {
            string errorMessage = "";
            bool   isError      = false;

            //string oguid = guid;
            // guid = hashGuid(guid);


            //validate regToken

            bool isTokenValid = false;

            string tok = "";

            NpgsqlConnection conn = new NpgsqlConnection(_connstrWallet);

            conn.Open();
            try
            {
                //first validate the token provided
                //to autorise the temporary device token
                string        sql = "sp_getemailtoken";
                NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new NpgsqlParameter("p_walletid", guid));
                cmd.Parameters.Add(new NpgsqlParameter("p_emailvalidationtoken", twoFactorToken));
                NpgsqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    reader.Read();
                    DateTime expiry    = reader.GetDateTime(0);
                    int      tokenType = reader.GetInt32(1);

                    if (expiry > DateTime.Now)
                    {
                        isTokenValid = true;
                    }
                }
                reader.Dispose();

                if (isTokenValid)
                {
                    byte[] devkey = new byte[32];

                    _csprng.getRandomValues(devkey);

                    tok = HexString.FromByteArray(devkey);
                    tok = Helper.hashGuid(tok);

                    cmd             = new NpgsqlCommand("sp_createemailtoken", conn);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new NpgsqlParameter("p_emailvalidationtoken", tok));
                    cmd.Parameters.Add(new NpgsqlParameter("p_walletid", guid));
                    cmd.Parameters.Add(new NpgsqlParameter("p_emailaddress", ""));
                    cmd.Parameters.Add(new NpgsqlParameter("p_expirydate", DateTime.Now.AddMinutes(10)));
                    int tmpisu = 0;
                    cmd.Parameters.Add(new NpgsqlParameter("p_isused", tmpisu));
                    cmd.Parameters.Add(new NpgsqlParameter("p_tokentype", 6));
                    cmd.ExecuteNonQuery();
                }
                else
                {
                    isError      = true;
                    errorMessage = "ErrInvalid";
                }
            }
            catch (Exception ex)
            {
                isError      = true;
                errorMessage = "ErrInvalid";
            }
            finally
            {
                conn.Close();
            }

            if (isError)
            {
                return(Json(new ErrorObject(errorMessage)));
            }
            else
            {
                dynamic ret = new System.Dynamic.ExpandoObject();
                ret.message = tok;
                return(Json(ret));
            }
        }
Exemple #30
0
        public void TestAsBase64(String hex, String base64)
        {
            HexString hs = new HexString(hex);

            Assert.Equal(base64, hs.asBase64());
        }