UPDATE 1:

I have changed the StringBuilder, and am now using objects and then serializing the object using Newtonsoft.Json.


MY SECOND ATTEMPT TO USE THE API REFERENCE CODE FROM https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)#.NET_.28C.23.29:

private void button1_Click(object sender, EventArgs e)
{
    JContainer jArray = new JArray();

    JObject jFromTx = new JObject
    {
        { "txid", data["result"][Convert.ToInt32(txtFromJSON.Text)]["txid"] },
        { "vout", data["result"][Convert.ToInt32(txtFromJSON.Text)]["vout"] }
    };

    jArray.Add(jFromTx);

    JObject jToTx = new JObject
    {
        { Convert.ToString(data["result"][Convert.ToInt32(txtToJSON.Text)]["address"]), Convert.ToDouble(txtAmountToSpend.Text) }
    };

    JContainer jArray2 = new JArray
    {
        jToTx
    };

    string strFrom = JsonConvert.SerializeObject(jArray);
    string strTo = JsonConvert.SerializeObject(jArray2);

    data = JObject.Parse(RequestServer("createrawtransaction", new List<string>() { strFrom, strTo }));
}

THE NEW SERIALIZED JSON:

{"jsonrpc":"1.0","id":"1","method":"createrawtransaction","params":["[{\"txid\":\"1a43a1f27c5837d5319a45217aa948a4d39c1d89faf497ce59de5bd570a64a26\",\"vout\":1}]","[{\"2NAZpRsvj9BstxxCDkKoe1FVjmPPxdmvqKj\":0.01}]"]}

THE OLD STRINGBUILDER JSON:

{"jsonrpc":"1.0","id":"1","method":"createrawtransaction","params":["[{\"txid\":\"1a43a1f27c5837d5319a45217aa948a4d39c1d89faf497ce59de5bd570a64a26\",\"vout\":1}]","[{\"2NAZpRsvj9BstxxCDkKoe1FVjmPPxdmvqKj\":0.01}]"]}

ATTEMPT TWO ERROR MESSAGE:

System.Net.WebException
  HResult=0x80131509
  Message=The remote server returned an error: (500) Internal Server Error.
  Source=RawTransactions
  StackTrace:
   at RawTransactions.Form1.RequestServer(String methodName, List`1 parameters) in C:\Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Form1.cs:line 184
   at RawTransactions.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Form1.cs:line 129
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at RawTransactions.Program.Main() in C:\Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Program.cs:line 19

ORIGINAL QUESTION:

Trying to post to a local bitcoin full note via json-rpc.


SOURCE FROM:

Following the examples here: https://bitcoincore.org/en/doc/0.17.0/rpc/rawtransactions/createrawtransaction/

I can see the following example structure:

{"jsonrpc": "1.0", "id":"curltest", "method": "createrawtransaction", "params": ["[{\"txid\":\"myid\",\"vout\":0}]", "[{\"address\":0.01}]"] }

WHAT I HAVE TRIED:

My code creates the following structure:

{"jsonrpc":"1.0","id":"1","method":"createrawtransaction","params":["[{\"txid\":\"1a43a1f27c5837d5319a45217aa948a4d39c1d89faf497ce59de5bd570a64a26\",\"vout\":1}]","[{\"2NAZpRsvj9BstxxCDkKoe1FVjmPPxdmvqKj\":0.01}]"]}

ERROR MESSAGE:

The json my code is creating seems to match the structure of the example from bitcoincore.org, but it gives an error:

System.Net.WebException
  HResult=0x80131509
  Message=The remote server returned an error: (500) Internal Server Error.
  Source=RawTransactions
  StackTrace:
   at RawTransactions.Form1.RequestServer(String methodName, List`1 parameters) in C:\Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Form1.cs:line 132
   at RawTransactions.Form1.button1_Click(Object sender, EventArgs e) in C:\Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Form1.cs:line 77
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnClick(EventArgs e)
   at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ButtonBase.WndProc(Message& m)
   at System.Windows.Forms.Button.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.Run(Form mainForm)
   at RawTransactions.Program.Main() in C:\Users\userthree\Documents\Visual Studio 2017\Projects\RawTransactions\RawTransactions\Program.cs:line 19

THE CODE:

https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)#.NET_.28C.23.29

public static string RequestServer(string methodName, List<string> parameters)
{
    string ServerIp = "http://localhost:18332";
    string UserName = "USERNAME";
    string Password = "PASSWORD";

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(ServerIp);
    webRequest.Credentials = new NetworkCredential(UserName, Password);

    webRequest.ContentType = "application/json-rpc";
    webRequest.Method = "POST";

    string respVal = string.Empty;

    JObject joe = new JObject();
    joe.Add(new JProperty("jsonrpc", "1.0"));
    joe.Add(new JProperty("id", "1"));
    joe.Add(new JProperty("method", methodName));

    JArray props = new JArray();
    foreach (var parameter in parameters)
    {
        props.Add(parameter);
    }

    joe.Add(new JProperty("params", props));

    // serialize json for the request
    string s = JsonConvert.SerializeObject(joe);
    byte[] byteArray = Encoding.UTF8.GetBytes(s);
    webRequest.ContentLength = byteArray.Length;

    Stream dataStream = webRequest.GetRequestStream();
    dataStream.Write(byteArray, 0, byteArray.Length);
    dataStream.Close();

    StreamReader streamReader = null;
    try
    {
        WebResponse webResponse = webRequest.GetResponse();

        streamReader = new StreamReader(webResponse.GetResponseStream(), true);

        respVal = streamReader.ReadToEnd();
        var data = JsonConvert.DeserializeObject(respVal).ToString();
        return data;
    }
    catch (Exception exp)
    {
        throw (exp);
    }
    finally
    {
        if (streamReader != null)
        {
            streamReader.Close();
        }
    }

    return string.Empty;
}

MY ATTEMPT TO USE THE ABOVE CODE:

private void button1_Click(object sender, EventArgs e)
{
    StringBuilder sb1 = new StringBuilder();

    sb1.Append("[{\"");
    sb1.Append("txid");
    sb1.Append("\":\"");
    sb1.Append(Convert.ToString(data["result"][Convert.ToInt32(txtFromJSON.Text)]["txid"]));
    sb1.Append("\",\"");
    sb1.Append("vout");
    sb1.Append("\":");
    sb1.Append(Convert.ToString(data["result"][Convert.ToInt32(txtFromJSON.Text)]["vout"]));
    sb1.Append("}]");

    StringBuilder sb2 = new StringBuilder();

    sb2.Append("[{\"");
    sb2.Append(Convert.ToString(data["result"][Convert.ToInt32(txtToJSON.Text)]["address"]));
    sb2.Append("\":");
    sb2.Append(txtAmountToSpend.Text);
    sb2.Append("}]");

    // {"jsonrpc":"1.0","id":"1","method":"createrawtransaction","params":["[{\"txid\":\"1a43a1f27c5837d5319a45217aa948a4d39c1d89faf497ce59de5bd570a64a26\",\"vout\":1}]","[{\"2NAZpRsvj9BstxxCDkKoe1FVjmPPxdmvqKj\":0.01}]"]}
    data = JObject.Parse(RequestServer("createrawtransaction", new List<string>() { Convert.ToString(sb1), Convert.ToString(sb2) }));

    MessageBox.Show(Convert.ToString(data));
}

OTHER COMMANDS WORK:

Other commands such as do work:

// {"jsonrpc":"1.0","id":"1","method":"sendtoaddress","params":["2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF","0.1"]}
data = JObject.Parse(RequestServer("sendtoaddress", new List<string>() { "2N8hwP1WmJrFF5QWABn38y63uYLhnJYJYTF", Convert.ToString(0.1) } ));

This also works:

// {"jsonrpc":"1.0","id":"1","method":"listunspent","params":[]}
data = JObject.Parse(RequestServer("listunspent", new List<String>() { }));

THE QUESTION:

What have I done wrong with createrawtransaction?

This question has an open bounty worth +50 reputation from oshirowanen ending tomorrow.

The question is widely applicable to a large audience. A detailed canonical answer is required to address all the concerns.

  • You shouldn't send the "backslash" with your request, the backslash there, is just to ignore the double quotes, but as final, the RPC server shouldn't receive that. – Adam Dec 3 at 23:00
  • @Adam - I can't see to remove the backslashes. Instead I have added update 1 in an attempt to use objects and then serialize the object to valid json. But I still get the same error message. – oshirowanen Dec 5 at 20:06
  • Is it possible for you to print out the contents of the RequestServer that has the final request so that we can see what ultimately gets sent to the server? – Andrew Chow Dec 6 at 15:05
  • Just in case is there any reason you don't use NBitcoin? – sipwiz Dec 6 at 19:55

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.