Click here to Skip to main content
15,886,110 members
Articles / Programming Languages / C# 3.5

How to Program Crypto Currency Transactions API on Windows with Crimeacoin

Rate me:
Please Sign up or sign in to vote.
4.76/5 (5 votes)
27 Mar 2014CPOL8 min read 27.7K   254   8   8
The article explains step-by-step how to start programming using cryptocurrency API for Bitcoin, Litecoin, CrimeaCoin, etc. The working example has been written for Crimeacoin.

Introduction

There is a new innovative invention on the Internet. It is called crypto currency! Even though television brought a lot of negativity about the first cryptocurrency called Bitcoin, I still think this kind of digital money is the future. The contradictions that we heard about Bitcoins can easily be positive features in the future. Let me explain what I mean.

I worked a lot with credit card networks. For example, one of my jobs was working for merchants who used credit cards for online payments, along with PayPal. Furthermore, I worked for one of the biggest credit card issuers in the world. Therefore, I think I know something when I say that serving credit card transactions on the Internet is not as great as it seems to be.

There is a lot of fraud with credit card transactions. Especially on the Internet… specifically when selling items that do not require shipping to physical addresses. As a customer, government laws cover you in case somebody steals your credit card information on the Internet and pays with it in stores. The government orders credit card issuers to return money to customers in such cases. Even if the credit card was not stolen and the transaction took place, it is still very plausible to ask for a refund from the merchant. Even if the merchant refuses, it is very easy for the customer to call the bank and initiate a chargeback. One might think that all money losses belong to a credit card issuer. I have heard this opinion time after time on major news channels such as CNN reporting about Target credit cards data breach. They are wrong - next the merchant who accepts stolen credit card covers all losses! What happens is the victim of credit card theft calls the credit card issuer or bank a few days, weeks, or months after the fraudulent transaction took place. The person initiates a chargeback. Then, the credit card issuer takes the money back from the merchant and waits for it, taking extra chargeback handling fees, which usually are 10 to 20 dollars per open cases.

So in the famous Target data breach, who suffered? Target? Maybe a little bit with their brand. Customers? They returned all their stolen money back! Credit card issuers? Definitely not, they took money from the merchants who served all that stolen cards after Target security breach! Credit card issuers even made a lot of money charging chargeback fees from merchants.

Cryptocurrency eliminates these chargeback issues! Transactions with objects like Bitcon provide no information about a customer’s wallet. The only two things you need to worry about when initiating an online transaction with cryptocurrency are receiver addresses and the amount! The seller gives a specific address for payment and the buyer sends money to the address. This eliminates the merchant’s hustle with possible fraudulent transactions, so these transactions become less anonymous. The buyer doesn’t pass his sensitive personal billing information to the seller. Furthermore, the seller does not need to worry about future chargeback fees. This is just one major positive, which is already leading this economic revolution into our modern material world.

The second most important thing is why cryptocurrency will beat credit card payments: There are almost no transaction fees. Credit card issuers create extremely massive tables with all those accumulating fees for merchants. If the merchant wants to accept a credit card, he or she pays five to ten percent of the money to credit card issuer. This reflects in the sold product prices. (And you thought those reward points for your credit card were from nowhere…)

Do you agree with me now that cryptocurrency is one of the biggest inventions since credit cards?

CrimeaCoin is a new cryptocurrency.

I have chosen this cryptocurrency because it is new to the market. It derives from Litecoin source codes. Also, the Litecoin was born from the Bitcoin. CrimeaCoin is based off of the “scrypt” algorithm if you want to know.

Those factors are important for our example:

1. You do not need to spend any money on testing the code to run yet. When a coin is young, it is very easy in earlier stage to mine for them. CrimeaCoin.org has a very detailed guide on how to mine their coins: http://www.crimeacoin.org/crimeacoin-mining-explained.aspx. I mined for 10 minutes and received around 200 coins. Who knows, perhaps these coins could be worth a lot of real money in the future.

There is a working compiled CrimeaCoin service/daemon app for Windows, which can be run as a scheduled task on the server. This app will be listening for RPC calls via socket connections. The name of it is crimeacoind.exe.

Using the Code

Setting Up the Environment

You need to setup and run the CrimeaCoin daemon. Download link is available from the developer's page.

Try launching it from the command line. It will give you a warning that configuration file is missing.

Make sure you have crimeacoin.conf file in the following location: C:\Users\yourusername\AppData\Roaming\crimeacoin. It is a configuration file for CrimeaCoin daemon and for a wallet GUI application. You can install GUI wallet too if you would like to.

This location also holds debug.log file and the Crimeacoin blocks will be downloaded here as needed. These are few essential lines you have to have in the conf file:

server=1
rpcuser=yourcrimeacoinusername
rpcpassword=verylongpasswordthatcanbeguessed
rpctimeout=60
rpcallowip=127.0.0.1
rpcport=29332

Server setting means that the daemon will be running its own RPC server on your Windows machine. Rpcuser and rpcpassword are required for the operations with the CrimeaCoin wallet API. Come up with some complicated ones. Rpcallowip should only have the IP of the machine which calls the daemon. Otherwise, some hackers can steal your CrimeaCoins as a worst case scenario. Rpcport tells daemon to listen for incoming connections on this port. Go ahead and change it if needed.

Now you can launch crimeacoind.exe from the command line.

While the exe-file is running, launch a second command line and type in “crimeacoind.exe getinfo”. Hit enter. You should see something similar to this:

c:\Program Files\CrimeaCoin>crimeacoind.exe getinfo
{
"version" : 90000,
"protocolversion" : 70002,
"walletversion" : 60000,
"balance" : 135.06597672,
"blocks" : 1285,
"timeoffset" : 0,
"connections" : 3,
"proxy" : "",
"difficulty" : 0.17470968,
"testnet" : false,
"keypoololdest" : 1394941152,
"keypoolsize" : 112,
"paytxfee" : 0.00000000,
"mininput" : 0.00001000,
"errors" : ""
} 

That means the daemon is up and running. You can even read the debug.log to check if it is connecting to the CrimeaCoin network.

Now it is time for some C# coding.

RPC-calls to the CrimeaCoin Wallet

I have attached the simple console application to this article. You can download it. The first thing you need to do in order to change the following values in your .NET app config file according to your CrimeaCoin daemon settings:

XML
<appSettings>
  <add key="CrimeacoinDaemonUrl" value="http://localhost.:29332"/>
  <add key="CrimeacoinRpcUsername" value="yourcrimeacoinusername"/>
  <add key="CrimeacoinRpcPassword" value="verylongpasswordthatcanbeguessed"/>
  <add key="CrimeacoinRpcRequestTimeoutInSeconds" value="60"/>
</appSettings>

Once those are modified, you can start making the RPC-requests to CrimeaCoin wallet. It is running locally in my case. The calls are going via http requests. Authorization for connection to CrimeaCoin wallet is required. For this purpose, I set up a username and password in the code:

C#
//Setting up authorization info
            String authInfo = ConfigurationManager.AppSettings["CrimeacoinRpcUsername"] + 
            ":" + ConfigurationManager.AppSettings["CrimeacoinRpcPassword"];
            authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
            webRequest.Headers["Authorization"] = "Basic " + authInfo; 

Create a New Receiving Address Per Transaction or Per Buyer

The nature of virtual currency transaction does not allow others to find out who was a sender, which is mostly a good thing. Therefore, we need to make a new address per customer or even per transaction. If you sell a book to John Doe, you must give him a unique CrimeaCoin address for sending money to. Once you will see incoming coins in your wallet, you will know what receive address has been used to transmit the money.

So, there is a RPC call to generate new address “getnewaddress”. My function is pretty straight forward:

C#
public GetNewAddressResponse getNewAddress()
        {   CrimeacoinRpcRequest newAddressRequest = new CrimeacoinRpcRequest(1, "getnewaddress", null);
            HttpWebRequest webRequest = MakeHttpRequest(newAddressRequest);
            string jsonResponse = GetJsonResponse(webRequest);
            JavaScriptSerializer jsSer = new JavaScriptSerializer();
            return (GetNewAddressResponse)jsSer.Deserialize<GetNewAddressResponse>(jsonResponse);
        } 

Waiting for payment confirmation

Once you have given the unique receiving address to the customer, you have to wait for incoming transactions. This part is a little bit tricky. Because of the nature of peer-to-peer of virtual currencies, there can be some problems with double spending. Double spending brought down the Mt Gox exchange giant, I’m sure you’ve heard of it. Luckily, there is a simple technique to ensure your online store is not getting abused by some smart hackers.

All CrimeaCoin transactions are hashed block by block. Every single transaction of the past is a part of the current block and the future blocks. Furthermore, CrimeaCoin blocks are calculated fast enough. One block is produced every two to five minutes as I write this article. If you see the block, which carries your customer’s transaction to you, wait for another block(s). Every additional block is reducing the probability of double spending. If you wait for five confirmation blocks, you have a 99.99% probability that the transaction is solid.

As an option, you can mark the order authorized in your online store system after the first block with the transaction. Then you can change the order into settle state after five or more block confirmations.

Let’s see how we can scan for new incoming transactions and check the confirmation number. I have received a few coins in my wallet and I am reading the information.

We are going to use CrimeaCoin API call “listtransactions”. Optional parameters are [account] [count=10] [from=0]. The description is:

Returns up to [count] most recent transactions skipping the first [from] transactions for account [account]. If [account] not provided will return recent transaction from all accounts.

I am going to check last 10 transactions.

C#
public ListTransactionsResponse listTransactions()
{   CrimeacoinRpcRequest newAddressRequest =
            new CrimeacoinRpcRequest(2, "listtransactions", null);
    HttpWebRequest webRequest = MakeHttpRequest(newAddressRequest);
    string jsonResponse = GetJsonResponse(webRequest);
    JavaScriptSerializer jsSer = new JavaScriptSerializer();
    return (ListTransactionsResponse)jsSer.Deserialize<ListTransactionsResponse>(jsonResponse);
}

My output shows me the following:

Transaction address :
CarDXKkcv8Cw3Mi9V5h6dVCxh9GTwV6zEf
Transaction Amount :
0.61206407
Confirmation count : 4
Transaction address :
CarDXKkcv8Cw3Mi9V5h6dVCxh9GTwV6zEf
Transaction Amount :
1.81192974
Confirmation count : 2
Transaction address :
CarDXKkcv8Cw3Mi9V5h6dVCxh9GTwV6zEf
Transaction Amount :
2.23472546
Confirmation count : 0 

You may be better at checking the funds with this API call:

  • Method: Getreceivedbyaddress
  • Parameter: <crimeacoinaddress> [minconf=1]
  • Description: Returns the total amount received by < crimeacoinaddress> in transactions with at least [minconf] confirmations. While some might consider this obvious, value reported by this only considers *receiving* transactions. It does not check payments that have been made *from* this address. In other words, this is not "getaddressbalance". Works only for addresses in the local wallet, external addresses will always show 0.

Points of Interest

I have learned that programming virtual currency API brings e-commerce to the new evolution level. It is easier to use CrimeaCoins when buying or selling goods on the Internet than credit cards. A straightforward mechanism of transferring cryptocoins allows saving a lot of money when eliminating outdated credit card transaction merchant fees.

Buyers do not need to trust their sensitive billing information in the hands of online merchants when doing cryptocurrency transactions.

History

  • 03/25/2014 - Submitted original version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionGetBalance Pin
710viv1-Jun-16 23:47
professional710viv1-Jun-16 23:47 
QuestionNBitcoin Pin
710viv1-Jun-16 23:43
professional710viv1-Jun-16 23:43 
QuestionQuestion on error running code Pin
dennis121528-Jun-14 11:56
dennis121528-Jun-14 11:56 
QuestionProblem with crimeacoind Pin
Gary Davis29-Mar-14 12:42
Gary Davis29-Mar-14 12:42 
AnswerRe: Problem with crimeacoind Pin
Sergey Nizhegorodtsev29-Mar-14 13:01
Sergey Nizhegorodtsev29-Mar-14 13:01 
AnswerRe: Problem with crimeacoind Pin
Sergey Nizhegorodtsev29-Mar-14 13:52
Sergey Nizhegorodtsev29-Mar-14 13:52 
GeneralRe: Problem with crimeacoind Pin
Gary Davis30-Mar-14 4:10
Gary Davis30-Mar-14 4:10 
GeneralMy vote of 5 Pin
Volynsky Alex27-Mar-14 7:57
professionalVolynsky Alex27-Mar-14 7:57 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.