Author

Topic: C# JSON-RPC issue with importprivkey (Read 2011 times)

newbie
Activity: 30
Merit: 0
April 03, 2013, 02:54:53 PM
#2
OK, I answer myself.

Code:
using System;
using System.Text;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        static void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
        {
            string authInfo = userName + ":" + userPassword;
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            request.Headers["Authorization"] = "Basic " + authInfo;
        }
        
        static void Main(string[] args)
        {
            string postData = "{\"jsonrpc\": \"1.0\", \"id\":\"1\", \"method\": \"importprivkey\", \"params\": [\"5xxxxPRIVATEKEYHERExxxxxxxxxx\", \"NewKeyName\", false] }";
            //string postData = "{\"jsonrpc\":\"1.0\",\"id\":\"1\",\"method\":\"getbalance\"}";

            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://10.0.0.30:8332");

            SetBasicAuthHeader(request, "rpc_username", "rpc_password");
            
            request.Method = "POST";
            request.ContentType = "application/json-rpc";    
            request.ContentLength = postData.Length;

            System.IO.Stream writeStream = request.GetRequestStream();
            UTF8Encoding encoding = new UTF8Encoding();
            byte[] bytes = encoding.GetBytes(postData);
            writeStream.Write(bytes, 0, bytes.Length);
            writeStream.Close();
        }
    }
}


SetBasicAuthHeader is needed as bitcoind is not requesting the login infos, we have to push them into it.
I don't like third party dlls, so this solution is clean and simple.
newbie
Activity: 30
Merit: 0
April 03, 2013, 12:15:49 PM
#1
Anyone has a working demo how to use importprivkey with C# for JSON-RPC ?

I tested that command with these C# API projects:

https://github.com/mb300sd/Bitcoin.NET
http://sourceforge.net/projects/bitnet

In both cases the console crashes with an exception:
"The remote server returned an error: (500) Internal Server Error."

GetBalance works in both projects.

Calling bitcoind from cmd.exe using the importprivkey tags works fine.
However I noticed that bitcoind returns nothing when a key is sucessfully added or returns an error message when the key already existed.

So what now ?  Huh

Jump to: