Bitcoin Forum
November 07, 2024, 04:27:14 AM *
News: Latest Bitcoin Core release: 28.0 [Torrent]
 
   Home   Help Search Login Register More  
Pages: [1]
  Print  
Author Topic: C# JSON-RPC issue with importprivkey  (Read 2024 times)
PoorGirl (OP)
Newbie
*
Offline Offline

Activity: 30
Merit: 0



View Profile
April 03, 2013, 04: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

PoorGirl (OP)
Newbie
*
Offline Offline

Activity: 30
Merit: 0



View Profile
April 03, 2013, 06: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.
Pages: [1]
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.19 | SMF © 2006-2009, Simple Machines Valid XHTML 1.0! Valid CSS!