Coding for NXT Crypto Platform #1

Coding for NXT Crypto Platform #1: Configuration

Setting up the config File

The configuration file of Nxt is an important tool for you to setup how Nxt works on your computer.

With the configuration file, you can setup your Nxt to use SSL, Setup Nxt on a Raspberry Pi or configure your Nxt for development, like the example used here.

The configuration file

You already have a configuration file you can see all current settings

nxt/conf/nxt-default.properties

For developing purposes, please create a file in nxt/conf/ and name it nxt.properties

Please copy the code below in your nxt.properties file.

# Enable Cross Origin Filter for the API server.
nxt.apiServerCORS=true

# Enable Cross Origin Filter for NRS user interface server.
nxt.uiServerCORS=true

If you want to develop on testnet, please add

# Never unlock your real accounts on testnet! Use separate accounts for testing only.
# When using testnet, all custom port settings will be ignored,
# and hardcoded ports of 6874 (peer networking), 6875 (UI) and 6876 (API) will be used.
nxt.isTestnet=true

Instead of hosting Nxt yourself, you can decide to get information from any other node in the Nxt network. In my examples, I will be using http://localhost:7876. This is when you are using Nxt on your personal computer or server. A list of other nodes you could use for displaying data on your website or access Nxt can be found on websites that provide access to the Nxt network like Nxtpeers.com or PeerExplorer.com

Instead of using http://localhost:7876 you could then, for example, enter an IP like http://x.x.x.x:7876 to get information from a node instead of localhost.

When you want to have control over the node, which version it runs, which information can be accessed or how many data sets the API retrieves, it makes sense to have your own node running with the configuration you prefer.

If you are looking for more information on the API, documentation and more I recommend the Nxt Wiki.

Find also how to create your own public node or host your node with amazon AWS.

Read the next part of this series > …

By: Tosch

Also see: http://nxter.org/developers

Coding for NXT Crypto Platform #2

Coding for NXT Crypto Platform #2: First Steps

About Nxt

Did you ever want to participate in a financial field with your Software without taking big risks and have an easy and anonymous access to? Have you tried to access monetary systems and get transparent data from Asset Exchanges, Marketplaces, Data clouds? Nxt is a peer-to-peer Blockchain Software that allows a global financial service that you can use on your server or computer. No registration, no bureaucracy.

What does the Nxt Blockchain bring to the table that is new?

In traditional banking systems you encounter ‘trusted’ banks which manage your money and holdings for you as a service. But when you want to access your money they do not make it easy for you. Especially as a developer, there is no chance you can retrieve the data of holdings or have access to the historical Wall Street data for free.

With the peer-to-peer blockchain system Nxt has started to build a whole ecosystem around secure and transparent data handling. You can start your own services, create currencies, create assets and trade them, a built-in marketplace, data cloud and much more!

Getting started

With the following lines of code I would like to demonstrate how to get a first access to Nxt data and then show you how to write on the blockchain and get some data ready for your homepage.

From there you could start building everything you can imagine around the Blockchain, Account Ledger and featured tools.

If you have not installed it yet, see here how to install and configure Nxt to start developing.

“Hello World”

In this example, we are choosing the most basic setup which lets you display data from the Blockchain on your website.

We will use JQuery to simplify the API call but you can achieve the same results with other frameworks or a bit more code.

Let us create the first html file, we call it transaction.html and insert the following code into it.

<div id="result"></div>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
      $.getJSON('http://localhost:7876/nxt', {"requestType": "getTransaction", "transaction": "8520011591947303971"}, function(request) 
      {
        $("#result").html(request.attachment.message);
      });
  </script>

Nxt has a very helpful API documentation that is addressable on http://localhost:7876/test. We are using the getTransaction call in this example, which you can also test on the API page.

When running the script above, you should see the following response in your Browser:

Hello World
Congratulations! You have received the first data from the blockchain

But what happened here?

First, we have used the API call “getTransaction” which allows us to have a detailed look at information of any transaction that is on the Blockchain. Have a look at your browser console to see the whole transaction information.

In the above code, we have accessed the market output of the JSON response the Nxt API gave us. Here you can see the whole object returned from the API.

{
                            "senderPublicKey": "7969c2ec61af9bedd3260c9b2cd4a292ba01ecbc2901a86851fa6c68208b0766",
                            "signature": "d13ad29034e56ae58b7f1eee4979cd6dffff38a7a26094c86103e431faf0bd06084be1e42534efd8e76b8a59c12630b52d851c571a25bc54af9ebdb56ca6df14",
                            "feeNQT": "100000000",
                            "requestProcessingTime": 0,
                            "type": 0,
                            "fullHash": "23bc3ae466293d7690b426173445e5b87423ea798b1d9c2913feda5d0d52a5b6",
                            "version": 1,
                            "phased": false,
                            "ecBlockId": "15499194118663359315",
                            "signatureHash": "9ea43451798a0144bd6cea58cbbba479c24ed7cdc29a4077a9aeb49a063498a7",
                            "attachment": {
                                "version.Message": 1,
                                "messageIsText": true,
                                "message": "Hello World",
                                "version.OrdinaryPayment": 0
                            },
                            "senderRS": "NXT-5RB8-KJD3-BT3B-E2QWW",
                            "subtype": 0,
                            "amountNQT": "10000000000",
                            "sender": "14876164227056393510",
                            "recipientRS": "NXT-P439-YVBD-VUEQ-A3S2T",
                            "recipient": "10124938546868029479",
                            "ecBlockHeight": 614717,
                            "deadline": 1440,
                            "transaction": "8520011591947303971",
                            "timestamp": 67508752,
                            "height": 2147483647
                        }

Why use getJSON?

As we have been using the getJSON function of Jquery, we do not need to parse the JSON anymore and can directly access JSON the Nxt API returns. When using an ajax call or get method of Jquery, you might need to JSON.parse(request) in order to access the object.

The transaction 8520011591947303971 we have accessed in the code, was a transaction I have previously sent. Every transaction within Nxt is transparent and for everybody to see. Have a look at the returned JSON from the Nxt API and with your script at hand you can already display all the information you are interested in from any transaction.

Replace the request.attachment.message (with for example request.accountRS) to display the account ID and continue with adding a nice view to the information.

In the following articles, I will show you how to submit the first data on the blockchain. How to retrieve data from Assets, calculate prices and see running orders.

Reaching for the stars

Nxt supports you in creating computer Software that allows trading on a global space in a peer-to-peer network where every participant is equal in power. Start building awesome things with Nxt.

Read the next article in this series > …

More in this series:
Coding for NXT Crypto Platform #1: Configuration

Also see: http://nxter.org/developers

Coding for NXT Crypto Platform #3: Output from the Asset Exchange

Coding for NXT Crypto Platform #3: Output from the Asset Exchange

The Star of Blockchains

Welcome to the third article on coding with NXT. In the previous articles I have shown you how to set up your Nxt configuration file to easily develop with JavaScript and how to get the first output from the Blockchain data. In this article I would like to continue with one of the most widely used tools in Nxt: the Asset Exchange.

What is the Asset Exchange?

The Asset Exchange is an Exchange based on Blockchain technology. Everybody can to create his/her own Asset tokens on the Blockchain. The Asset can represent anything , whether it is financial services, crowdfunding, support for a website, memberships, commodities or other things you can imagine.

The benefit of using an Asset token on the Nxt Blockchain is that you directly have a global audience, as the Internet and digital currencies such as Nxt or Bitcoin do not know borders. Another benefit I would like to highlight is that nobody needs a real bank account; once you hold your first virtual currency it is easy to move from one denomination to the other and because Blockchain technology is accesible to everyone, there is no difficulty to move them from person to person. (You still should inform yourself about your local juristriction and if creating such an Asset is allowed.)

How to retreive the first Asset Data

To get your first Data we first choose an Asset; you can see a list of all existing Nxt Assets here: Mynxt.info Asset List

Once you have chosen an Asset, you can see the Asset ID in the top left corner. We will need this ID to get data from an Asset. I have chosen the SuperNET Asset in this example as it is frequently traded and has a lot of historical data we can look at.

Please remember you need to have your instance of Nxt running on your system to follow the rest of this tutorial.

First, let us look at the Meta Data of an Asset. The following script will give you output of the original Asset Setup. As always, I recommend you the page http://localhost:7876/test when looking up the API calls. On this page you can see which calls are for receiving data (GET) or submitting data (POST) to the Blockchain. We will start with GET requests and the call getAsset.

You can use this script to display information on Assets on your website, to overview which Assets have been created in short or long term or just for a personal list of Assets and their functions.

<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
  <h2>Asset Data</h2>
  <table class="table table-striped">
    <thead>
      <tr>
        <th>Key</th>
        <th>Data</th>
      </tr>
    </thead>
    <tbody id="result">
      
    </tbody>
  </table>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

  <script>
      $.getJSON('http://localhost:7876/nxt', {"requestType": "getAsset", "asset": "12071612744977229797", "includeCounts": "true"}, function(request) {
        var rows;
        $.each(request, function(key, data) {
          rows += '<tr>';
          rows += '<td>'+key+'</td>';
          rows += '<td>'+data+'</td>';
          rows += '</tr>';
        });
        $("#result").html(rows);
      });
  </script>
</body>
</html>

The code above will display a table on your HTML page with the following information:

programming-nxt-3-1

I want to take some time to teach you about some abbreviations in Nxt at this point:

You see two variables “initialQuantityQNT” and “quantityQNT”. QNT stands for “Quantity”, the initialQuantity is setup by the Asset creator in the beginning. As some of the Assets might be deleted, the “quantityQNT” shows us how many Assets exist at the moment. We also need the “decimals” variable. The Asset we look at has 4 decimals, which means that the number of Assets shown in the table need to be divided by 10,000 (4 zeroes) to get the actual number. The above Asset would result in a quantity of currently 816,061.0000 Assets.

The Account is the numerical Nxt account of the Asset creator and the accountRS the same account identifier in Reed-Solomon (RS) format.

The numberOfTrades, numberOfTransfers and numberOfAccounts are calculated at the point in time when you run the call.

You can shorten the “getAsset” API call with leaving out “includeCounts”: “true” at the above $.getJSON call, consequently you will not receive the number of Asset holders, transfers and trades but the API call will get quicker.

Ask and Bid Orders

After learning details about the Asset and getting the Meta Data, we will want to know if there are Ask or Bid Orders for this Asset and at which price the Asset is currently traded. The methods to use calculatons from Quantities or Nxt decimal places are not always optimal. Sometimes I am choose the methods in this tutorial to be more understandable rather than optimal. Usually I would recommend to make calculations with the original numbers from the API. You won’t have to deal with decimal places and this is where most errors result from. The API calls we are using for this is getAskOrders and getBidOrders. Again, we need the Asset ID to get the Ask and Bid Orders for the Asset you are interested in. Additionally we will shorten the output by adding the firstIndex and lastIndex parameters. Here is the code to retreive both Ask and Bid Orders for the SuperNET Asset:

<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
  <div class="col-md-6">
    <h2>Ask Orders</h2>
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Account</th>
          <th>Quantity</th>
          <th>Price</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody id="askTable">
      
      </tbody>
    </table>
  </div>
  <div class="col-md-6">
    <h2>Bid Orders</h2>
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Account</th>
          <th>Quantity</th>
          <th>Price</th>
          <th>Total</th>
        </tr>
      </thead>
      <tbody id="bidTable">
      
      </tbody>
    </table>
  
  </div>
  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
  <script>
  
  $.getJSON('http://localhost:7876/nxt', {"requestType": "getAsset", "asset": "12071612744977229797"}, function(request) {
    var decimals = request.decimals;
    var NQTdivider = 8 - decimals;
    
    
      $.getJSON('http://localhost:7876/nxt', {"requestType": "getAskOrders", "asset": "12071612744977229797", "firstIndex": 0, "lastIndex": 4}, function(requestAskOrders) {
        var rows;
        $.each(requestAskOrders.askOrders, function(key, data) {
        
          var quantity = data.quantityQNT / Math.pow(10, decimals);
          var accountRS = data.accountRS;
          var priceNXT = data.priceNQT / Math.pow(10,NQTdivider);
          var total = quantity * priceNXT;
          
          rows += '<tr>';
          rows += '<td>'+accountRS+'</td>';
          rows += '<td>'+quantity+'</td>';
          rows += '<td>'+priceNXT+'</td>';
          rows += '<td>'+total+'</td>';
          rows += '</tr>';
        });
        $("#askTable").html(rows);
      });
        
      
      $.getJSON('http://localhost:7876/nxt', {"requestType": "getBidOrders", "asset": "12071612744977229797", "firstIndex": 0, "lastIndex": 4}, function(requestBidOrders) {
        var rows;
          $.each(requestBidOrders.bidOrders, function(key, data) {
          
            var quantity = data.quantityQNT / Math.pow(10, decimals);
            var accountRS = data.accountRS;
            var priceNXT = data.priceNQT / Math.pow(10,NQTdivider);
            var total = quantity * priceNXT;
            
            rows += '<tr>';
            rows += '<td>'+accountRS+'</td>';
            rows += '<td>'+quantity+'</td>';
            rows += '<td>'+priceNXT+'</td>';
            rows += '<td>'+total+'</td>';
            rows += '</tr>';
        });
        $("#bidTable").html(rows);
      });
    
    
    });
      
  </script>
</body>
</html>

With this call you are expected to receive 2 tables on your HTML page:

programming-nxt-3-2

The script above can be used to display current prices and Offers for an Asset on your website, and to show the whole Orderbook of any Asset. Furthermore you can use it and analyse tendencies. As you additionally have the Accounts for all bids and asks, you can analyze the bids and asks for the amount of Accounts that are trading on the platform.

This time we had to do some more $.getJSON queries to get the information we want. First, we need the decimals of the Assets to do the calculation about the Quantity as mentioned with the first call. Second, we want to get both: Ask and Bid orders. This needs one query for each of the API calls.

We also see a new variable that needs explanation. “priceNQT” is the price of an Asset per QuantityQNT.

The price on the API is displayed in priceNQT per QuantityQNT. So, what is NQT and what is the difference to QNT? NQT refers to NXTQuant, the smallest number we have in NXT, which is 0.00000001 NXT (8 decimal places). We also have to take into account the decimal places, which we have to multiply again to get the price per actual Asset. I have used the variable var NQTdivider = 8 — decimals; to get the number of power we need to divide the Quantity by and get the current price in NXT per Quantity.

I hope you have enjoyed this third installment of “Coding for NXT Crypto Platform”. In the next article, I will be covering Historical Data and Account information. If you have any questions, feel free to contact me via email or my Nxt Forum account.

Read the next article in this series > …

Also see: http://nxter.org/developers

More in this series:
Coding for NXT Crypto Platform #1: Configuration
Coding for NXT Crypto Platform #2: First Steps

by Tosch

Coding for NXT Crypto Platform #4: Historical Asset Data

Coding for NXT Crypto Platform #4: Historical Asset Data

In the last topic I showed you how to retrieve basic data about Assets from the Nxt Asset Exchange.

In this article I want to cover how to receive historical trades.
The API call we are using here is “getTrades”.’

Historical Trades

Historical trades can either be from any Account or from any Assets, we are continuing as we did before and get latest trades from the Asset SuperNET.

Again we will be using the parameters firstIndex and lastIndex to retreive only the last 10 entries. If you want to get more trades, just change lastIndex to a higher number or erase both firstIndex and lastIndex completely.

If you erase firstIndex and lastIndex it is possible that you get a limited number of entries — this can be setup in your Nxt configuration file. Have a look at the property: nxt.maxAPIRecords=100 and configure it to your needs (just when you are working without an admin password).

Now, let’s jump back to the code.

<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
  <div class="col-md-12">
    <h2>Trade History</h2>
    <table class="table table-striped">
      <thead>
        <tr>
          <th>Date</th>
          <th>Type</th>
          <th>Quantity</th>
          <th>Price</th>
          <th>Total</th>
          <th>Buyer</th>
          <th>Seller</th>
        </tr>
      </thead>
      <tbody id="tradeHistory">
      
      </tbody>
    </table>
  </div>
  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
  <script>
  
  $.getJSON('http://localhost:7876/nxt', {"requestType": "getTrades", "asset": "12071612744977229797", "firstIndex": 0, "lastIndex": 9, "includeAssetInfo": "true"}, function(request) {
        
    var trades = request.trades;
    var rows;
    var nxtTime = 1385294400;
    $.each(trades, function(key, data) {
      var decimals = data.decimals;
      var NQT_QNT = 8 - decimals;
      var quantityQNT = data.quantityQNT / Math.pow(10, decimals);
      var priceNQT = data.priceNQT / Math.pow(10, NQT_QNT);
      var total = data.quantityQNT * data.priceNQT / Math.pow(10,8);
      var NxtTimestamp = (+data.timestamp + +nxtTime) * 1000;
      var d = new Date(NxtTimestamp);
      rows += '<tr>';
        rows += '<td>'+d.toDateString()+'</td>';
        rows += '<td>'+data.tradeType+'</td>';
        rows += '<td>'+quantityQNT+'</td>';
        rows += '<td>'+priceNQT+'</td>';
        rows += '<td>'+total+'</td>';
        rows += '<td>'+data.buyerRS+'</td>';
        rows += '<td>'+data.sellerRS+'</td>';
      rows += '</tr>';
    });
    $("#tradeHistory").html(rows);
    
  });
      
  </script>
</body>
</html>

For the API request, as stated above, we limited the response by setting firstIndex and lastIndex to 10 entries. Furthermore, the includeAssetInfo set as true will show the decimal for the Asset and the Name of the Asset. This will make the call a bit slower but especially when we are looking at more than one Asset a very helpful addition.

Instead of including includeAssetInfo we could make a getAsset call to receive those parameters (when just looking at one Asset this might be recommended). But when you are looking at an Account last trades instead of an Asset, this can save a lot of work and time.

The most important calculations to mention for this script are the Nxt timestamp, quantity and price. They are calculated as already explained above.

Nxt Timestamp

Nxt has its own timestamp. Nxt was started November on Nov 24, 2013 12:00 am. In Nxt this would be timestamp 0. In Javascript this is 1385294400 (as Javascript started January 1, 1970, 00:00:00), but JavaScript uses Miliseconds, therefore we have to multiply 1000 to get there. As a result we need to add the given timestamp of Nxt to 1385294400 and add the miliseconds to retreive the timestamp in JavaScript.

Analysing the historical data will get you a lot of information about the frequency of trading and how many accounts have been trading an Asset. The more accounts are involved in trading, the better an Asset is spread among traders, which is usually a good sign. Of course, you have to be aware that you do not know the origin of Accounts. It is possible that one person creates multiple accounts and trades from all of these accounts. The Asset appears to be traded by more parties, which seems beneficial for the Asset owner, on the other hand people might create several accounts to track different types of holdings. In a lot of cases it makes sense for a user to have more than just one Account.

The above script will show you a table like this one:

programming-nxt-4-1

Account Information

As you already know, the Blockchain is fully transparent; you can see any transaction in the network and all the holdings of one account. It still enables you to write encrypted messages, which cannot be read by anybody but the person who holds the passphrase of either the sender or the recipient.
The next step for you is to find out how to create a nice interface to view Accounts. All the necessary steps to get there are explained here.

The API call needed to get Account information is getAccount. You could also use getAccountAssets to monitor Asset holdings but getAccount will show you all the holdings of one account.

A hint: as in the getTrades API, you can decide to include furter informations with includeLessors, includeAssets, includeCurrencies or includeEffectiveBalance.

Enjoy developing with Nxt! In the next article, we will explore creating transactions and more details about the Blockchain. If you have any questions, feel free to contact me via email or my Nxt Forum account.

Read the next article in this series > …

Also see: http://nxter.org/developers

More in this series:
Coding for NXT Crypto Platform #1: Configuration
Coding for NXT Crypto Platform #2: First Steps
Coding for NXT Crypto Platform #3: Output from the Asset Exchange

Coding for NXT Crypto Platform #5: Transactions on the Nxt Blockchain

Coding for NXT Crypto Platform #5: Transactions on the Nxt Blockchain

Nxt Blockchain

The Nxt Blockchain is the heart of Nxt. Every Transaction ever made is recorded on the Blockchain. The Blockchain is a decentralized database, which is saved on your computer. To prevent spam, for every transaction you have to pay fees in the native currency, which will be NXT for us using the Nxt Blockchain. In previous articles I have shown how to setup and configure your Nxt Software as well as how to read data, this time we write data on the Blockchain, starting with a simple example. Throughout the article, I want to focus on tools you can use while creating Transactions on Nxt.

Send Nxt

Codewise, creating a transaction on Nxt is very similar to reading data from the Blockchain; There are some topics we have to cover before creating our first transaction. To create a transaction, we first need a Nxt Account and some NXT, in order to pay for Blockchain fees. So, let us log in to Nxt and create our first account.

Create a Nxt account

In order to have a secure Nxt account, you need a strong passphrase. Working With virtual currencies we use the term passphrase instead of password, this describes strong entropy and should be more secure than a regular password. When you are using the official Nxt Client, you can use the implemented passphrase creation function, which will give you a passphrase which contains 12 words.

Create your own passphrase

You can also create your own passphrase, make sure it contains enough characters and entropy. To generate a passphrase it is recommended to use Software such as KeePass, LastPass, Dashlane or Online Tools like PasswordsGenerator.net or Fourmilab.ch.

Nxt passphrase generator

When running Nxt on http://localhost:7876 you will get to the client, a click on the link quoting

DON’T HAVE AN ACCOUNT? CLICK HERE TO CREATE ONE!

will bring you to the passphrase generator. Afterwards (or with your self-created passphrase), you can log in to your Account. If you do not have NXT yet, the quickest method is when you already got some virtual Currencies like Bitcoin, Litecoin, Ethereum or others. You can exchange them via Shapeshift or buy your coins on another exchange and transfer them to your wallet.

In the next steps, we use your passphrase to sign and broadcast transactions. Your passphrase can also be seen as your private Key.

Create the Transaction

With a secure passphrase, we can now look into the code of creating a send-NXT-Transaction. We send out 1 NXT to a recipient, which you see in the code and change it there for another recipient. Insert your passphrase in the following code and run it to create the transaction.

<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
    <div class="col-md-12">
        <h2>Outgoing Transaction JSON</h2>
        
    <div class="well" style="word-wrap:break-word;" id="transactionJSON"></div>
    </div>
  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
  <script>
  
  $.post('http://localhost:7876/nxt', {"requestType": "sendMoney", "recipient": "NXT-5RB8-KJD3-BT3B-E2QWW", "amountNQT": "100000000", "secretPhrase": "YourPassphrase", "feeNQT": "0", "deadline": "800", "broadcast": false}, function(request) {
  
        var response = JSON.parse(request);
        $("#transactionJSON").html(JSON.stringify( response , null, 4));
  
      });
      
  </script>
</body>
</html>

This script is creating a sendMoney transaction. As you see we have been changing the function used in previous articles $.getJSON to $.post. When creating transactions, it is necessary to switch to POST format instead of GET requests as with the previous functions. For reference to the API details, have a look at http://localhost:7876/test?requestType=sendMoney.

The output you see on the page contains various information, the variable feeNQT has been filled in with the correct information, you can check how much the fee is for the transaction you have created. You see the whole transactionJSON you have inserted in JSON format and you receive the transaction transactionBytes. The transactionBytes embeds all the transaction information you have in the transactionJSON.

The above created transaction will not be broadcasted to the network yet because we set “broadcast”: false in our object. When setting this true the transaction will be broadcasted and will cost you 1 NXT. As you can see, we do not need many variables to create our first transaction.

The recipe for a transaction is:

requestType sendMoney
recipient You can use either the RS format e.g. NXT-XXX-XXX-XXX-XXXX or the numerical account format
amountNQT The amount you want to send needs to be calculated in NQT, the smallest number in NXT (1 NXT / 10⁸ = 1 NQT)
secretPhrase Your secret passphrase
feeNQT Place 0 if you want the server to calculate minimum fees for you
deadline measured in minutes, when the transaction expires
broadcast false will not broadcast and just create the transaction. Set to true the transaction will be broadcast to other peers and will cost you NXT

Broadcast transaction

Now that we know how to create a sendMoney transaction that has not yet been broadcasted, we can use a script that looks similar to the above one to broadcast the transaction. To make it more understandable I am extending the above script with a button that takes the previously created transaction and transfers it to the network on submitting the button. Effectively when running the script you have your first (small, not yet secure!) interactive Nxt wallet.

<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body>
    <div class="col-md-12">
        <h2>Outgoing Transaction JSON</h2>
        
    <div class="well" style="word-wrap:break-word;" id="transactionJSON"></div>
    <button class="btn btn-primary" id="submitTransaction">Submit this transaction</button>
   
    <hr>
    <div id="broadcastedTransaction"></div>
    </div>
  <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
  <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
  <script>
  
  $.post('http://localhost:7876/nxt', {"requestType": "sendMoney", "recipient": "NXT-5RB8-KJD3-BT3B-E2QWW", "amountNQT": "100000000", "secretPhrase": "YourPassphrase", "feeNQT": "0", "deadline": "800", "broadcast": false}, function(request) {
  
        var response = JSON.parse(request);
        $("#transactionJSON").html(JSON.stringify( response , null, 4));
        $("#submitTransaction").on("click", function() {
          $.post('http://localhost:7876/nxt', {"requestType": "broadcastTransaction", "transactionBytes": response.transactionBytes}, function(broadcast) {
            var broadcastResponse = JSON.parse(broadcast);
            $("#broadcastedTransaction").html(JSON.stringify( broadcastResponse , null, 4));
          }); 
        });
      });
  </script>
</body>
</html>

Loading the site will directly load the transaction not yet broadcasted. As the button click function is nested within the first call, it can access the data from the transaction not broadcasted. To broadcast the transaction we use the following recipe

requestType broadcastTransaction
transactionBytes The transactionBytes we have created with the previous declared function.

With these few lines of code, we can create a transaction and broadcast it. Yet, we are still defining all the variables directly within the code. In the next articles, I am going to show you how to add encrypted messages to a transaction and how to get these data from a user input you have on the page. We will have a deeper look into phasing and pruning of transactions.

Also see: http://nxter.org/developers

More in this series:
Coding for NXT Crypto Platform #1: Configuration
Coding for NXT Crypto Platform #2: First Steps
Coding for NXT Crypto Platform #3: Output from the Asset Exchange
Coding for NXT Crypto Platform #4: Historical Asset Data

By Tosch

Beer, Betting and the Nxt Blockchain

Suppose you have a circle of friends who you meet with in a sports bar to drink beer, watch sports and make bets. You can make bets on the Nxt Blockchain and have a basic Python app automate it for you.

In my first article I introduced basics of a blockchain. As we learned, the most important value proposition of the blockchain is immutability of data submitted in transactions recorded into blocks, from which a blockchain is built.

Today I want to show how to build a simple but fully functional betting app in python. For the betting app that I present, immutability of data may be required, but in the case a bet should need to be canceled, the app can be modified to take into account this additional functionality.

Pre-requisites:
NRS (Nxt Reference software) 1.10.2: https://bitbucket.org/JeanLucPicard/nxt/downloads/Python 3 (or Python 2 with slightest modification). A beer or two (optional).

Application logic

A user submits a bet (transfers any amount of NXT coins) to the betting account and adds a public unencrypted attachment. In the attachment he should write the id of the bet, a colon and a number indicating his choice in the corresponding bet. Let’s give an example: the sports bar runs a bet which football team wins. They assign an ID to this game, let’s say “30”.

The choices are:
“1” – home team wins. “2” – other team wins. “3” – tie.

To bet on the victory of the home team, the player must submit a transaction of any amount of NXT, and attach a public unencrypted (for auditability) message with the content: 30:1

When the time comes, the betting host runs the app to find winners and process payments. The host can take a small fee for the service.

Implementation

The Nxt Server listens for queries on port 7876. If you run it on the same machine as your python code by default you must submit queries to http://127.0.0.1:7876/nxt

For our app we will need to import a few modules and write the function to submit queries which will be used a few times through the app.

import sys, json, re

def sendQuery(Query):
  from urllib import parse, request
  params = parse.urlencode(Query)
  headers = {"Content-type": "application/x-www-form-urlencoded", 
"Accept": "text/plain"}
  req = request.Request("http://127.0.0.1:7876/nxt", 
params.encode('utf-8'))
  response = request.urlopen(req)
  return response.read()
	
myAccount = "NXT-AAAA-BBBB-CCCC-DDDDD"
totalAmount = 0
serviceFee = 0.05
players = []
secretPhrase = "bla bla bla"

The function returns a JSON string to be decoded, with transactions and attachments to be parsed. Also a few variables are initialized.

Next we must query the betting account to fetch all incoming transactions.
This is the request you can send to the NXT server to execute this:

Query = {'requestType': 'getBlockchainTransactions', 
'account': myAccount, 'type': '0', 'subtype': '0', 'executedOnly': 'true'}

decode JSON and load it to a variable for further processing.

output = sendQuery(Query)
data = json.loads(output.decode('utf-8'))

As we have all the data now, we loop through the list and discard some of the transactions we don’t need. For instance, we don’t need to process outgoing transactions, so we continue the loop from the next item.

for i in data['transactions']:
  txAmount = i['amountNQT']
  txSender = i['senderRS']
  if txSender == myAccount:
      continue
  txRecipient = i['recipientRS']
  if txRecipient != myAccount:
      continue

Next we pull out the attachment, check if it is not encrypted and strip whitespace.

  line = i['attachment']['message']
  lineIsText = i['attachment']['messageIsText']
  if line.strip() != "" and lineIsText == True:
    line = line.strip()

Next step is to match the submitted message against the regular expression. It must satisfy the format “Number:Number”, the first number can be up to 3 digits.

    matchLine = re.match(r'(\d{1,3}:\d{1})(.*)', line, re.M|re.I)

If the attached message is of correct format we process it further…

The betting app accepts up to 3 command-line arguments: id of the game, the choice number that has won, and third optional parameter in double quotes to name the winner choice for verbosity in the payout message.

For instance, the betting host must run it like this:
python3 bet.py 30 1 “Home team wins”

The app will process transactions with game id 30 and rewards players who chose ‘1’.
The third argument can be omitted: python3 bet.py 30 1

Next we must calculate the sum of money submitted for our game, make a list of dictionaries of players who guessed the correct number, and calculate the total sum for distribution after the betting host gets his optional service cut.

    if matchLine:
      if matchLine.group(1).split(':')[0] == sys.argv[1]:
        totalAmount += int(txAmount)
        if matchLine.group(1).split(':')[1] == sys.argv[2]:
          d = {txSender: matchLine.group(1).split(':')[1], 
'amount': txAmount}
          players.append(dict(d))
afterFee = float(totalAmount - totalAmount * serviceFee)

We have winners in the ‘players’ list of dictionaries, we have money to distribute in ‘afterFee’, let us now process payouts.

sumCorrect = 0
for i in players:
  for key in i:
    if i[key] == sys.argv[2]:
      sumCorrect += float(i['amount'])
for i in players:
  for key in i:
    if i[key] == sys.argv[2]:
      t = float(i['amount']) * (afterFee / sumCorrect)
      if t > afterFee:
        strSendAmount = str(int(afterFee))
      else:
        strSendAmount = str(int(t))
      if len(sys.argv) > 3:
        reply = sys.argv[3]
      else:
        reply = sys.argv[2]
      message = "Payout for correct bet in poll " 
+ sys.argv[1] + "; your reply: " + reply
      Query = {'requestType': 'sendMoney', 'recipient': key, 
      'amountNQT': strSendAmount, 'secretPhrase': secretPhrase, 
      'feeNQT': '100000000', 'deadline': '1440', 'broadcast': 'true', 
'message': message, 'messageIsText': 'true', 'messageIsPrunable': 'true'}
      sendQuery(Query)

Needless to say the app can be improved to process errors, cancel bets or optionally allow other parameters in attached messages. Attached messages can be submitted with the Nxt Client (NRS) or from a web wallet that allows sending attachments.

To make transactions on the Nxt Blockchain you need NXT coins, which you can purchase directly, by exchanging Bitcoin for NXT or by attending the “Lucky Node” project by running a public Nxt node (Nxt server).

To learn how to participate in the Lucky node project, please visit https://nxtforum.org.

There are over a hundred API calls you can make to the Nxt server, a full list with mandatory and optional parameters and examples is available at https://nxtwiki.org/wiki/The_Nxt_API.

Cheers!

blockchain-betting

Programming the Nxt Blockchain for fun and profit

Blockchains can be useful in various applications, facing global audience and supporting company internal infrastructure. A blockchain is a distributed database, a copy of the blockchain is stored on each node in a peer-to-peer network. This extreme redundancy can be duely considered inefficient, but please stay with me for a couple of minutes of blockchain theory.

As each node validates all transactions recorded into the blockchain and as past transactions cannot be rolled back or tampered with like in traditional RDBMS, this redundancy makes the blockchain *immutable*, and that is a very important value proposition of blockchains. Immutability of data is something traditional databases cannot provide. You may or may not need immutability of data and trust-free confirmation that data hasn’t been altered.

In this tutorial I assume you do need this.

One of the most versatile and flexible blockchains is the Nxt Blockchain (https://nxt.org). It has over a hundred API calls https://nxtwiki.org/wiki/The_Nxt_API.

Today you will learn basics of programming the Nxt blockchain. I will use only two API calls in this tutorial. With over a hundred API calls opportunities for programmers are limitless.

Application logic

A customer of a company or an employee in an organization uploads a file through a web form.
The file is renamed to a unique name and is saved in some location on the server.

A year later the customer / employee needs to verify, using the Nxt Blockchain, that the file hadn’t been altered. For instance, this may be required for legal purposes. It doesn’t have to be files. Internal company memos can be hashed and stored in the database, to be verified in a future audit.

Nxt allows us to send and record arbitrary messages (AM) into its blockchain.

Every transaction on the blockchain comes at a fee. If the transaction size is large, it can be expensive; fortunately Nxt has a subtype of AM called prunable messages. These are pruned after 90 days which make them cheap, they are available for retrieval from archival nodes after 90 days.

The maximum size of an arbitrary message in the Nxt blockchain is approx. 42 KB, the size of one block. A prunable message of 1 KB costs 1 NXT ($0.03). 1 KB is enough to store a hash of a file and this is our final cost to permanently record one hash in the immutable distributed Nxt blockchain.

As the customer uploads a file I create a SHA256 hash of the file and store the hash in the database in the organization’s server. For simplicity I’ve chosen SQlite, but you can use Mysql, Postgresql, Oracle. I will use PDO to access SQlite database in PHP.

When we do not use the immutable database (blockchain), the file can be modified, the new hash of the modified file saved in the database, making it hard to prove the file was like this from the beginning.

Blockchain comes to the rescue

Every prunable message can be retrieved from archival nodes. Every record in the blockchain is immutable. You can be sure the hash of the file you uploaded a year ago, when it is retrieved from the blockchain, is the same hash. All you need now is compare it with the hash in the organization’s internal RDBMS.

Pre-requisites:
PHP with curl, json and some db extension (I use sqlite3). A web server is optional, you can use php-cli. Java 8 (Oracle or OpenJDK to run Nxt). Nxt reference software: https://nxtforum.org/nrs-releases/nrs-v1-10-1/.

Install the NRS (Nxt Reference Software (depending on the context interchangeably called Nxt Client or Nxt Server)) and create an account. Fund it with a few coins. You can exchange Bitcoin to NXT at an exchange service like https://shapeshift.io or exchange with someone at https://nxtforum.org. It is also possible to “mine” some free NXT as reward for running a node; http://test.nxter.org/the-forging-bounty-lottery-campaign-will-pay-5-million-in-rewards-to-forgers-and-nxt-nodes/.

First we create a simple database table for our application, nothing fancy, you can add more column types if you must store more information. I like to use DB Browser for SQLite of http://sqlitebrowser.org.

Let’s make an empty database ‘files.db’ and save it in /home/lurker10/phptutorial/files.db

Using DB Browser for SQLite create the following table.

CREATE TABLE "files" (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`txid` TEXT,
`hash` TEXT,
`uploadtime` TEXT,
`filename` TEXT
)

‘txid’ is the field for storing the id of a transaction we receive from Nxt when the transaction is accepted. It is unique. ‘hash’ is the sha256 hash of the file.

In this tutorial I skip the file upload part of code to keep it concise.

Let’s assume the file is already uploaded and stored on the web server. We define the file location variable in the code.

$uploadDir = "/home/lurker10/phptutorial/tmp/";
$fileName = "copy12345.tar";

By default the Nxt Server listens for API requests on port 7876. If you run it on the same machine as your php code, your code must send queries to http://127.0.0.1:7876/nxt

The other important variables are the passphrase of the Nxt account you’ve created and funded and the recipient’s account.

You can send the message to yourself, recipient can be your own account.

$host = "http://127.0.0.1:7876/nxt";
$secretPhrase = "your passphrase";
$recipientID = "NXT-XXXX-XXXX-XXXX-XXXXX";

The next part of code is the function that submits query using curl in a POST request.

To make a query we must define $payload and $payload_string variables and feed them to sendRequest(). It is possible to run the Nxt Server over HTTPS and use curl to verify the SSL certificate, but for this simple app we have disabled SSL verification in the curl connection.

Another point of interest is the $errorDescription, json-decoded from server response.

If there is a problem with the query (“Not enough funds” in your account when your balance is zero),
you must add error handling routine. I omit this too. For this app I assume the server responded properly, and return the response into the app for further processing.

function sendRequest($host, $payload, $payload_string) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 10000);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 10000);
curl_setopt($ch, CURLOPT_POST, count($payload));
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload_string);
$output = curl_exec($ch);
$curl_error = curl_error($ch);
curl_close($ch);
$errorDescription = trim(@json_decode($output)->errorDescription);
if ($errorDescription != "") { // perform error handling; return false; }
return $output;
}

As the file is uploaded already, I create a sha256 hash of the file and timestamp.

$fileHash = hash_file("sha256", $uploadDir.$fileName);
$txTime = time();

I will use PDO to work with the database.

Open the db and insert a new record.

We don’t know the txid until we talk to the Nxt Server that can give it to us when transaction is accepted on the NXT network, so for now I’ll insert null for txid.

$pdo = new PDO('sqlite:/home/lurker10/phptutorial/files.db');
$sql = "INSERT INTO files (txid, hash, uploadtime, filename)
VALUES (null, '$fileHash', '$txTime', '$fileName')";
$result = $pdo->exec($sql);

Next we create a query to send to the NXT server.

This particular query is “sendMessage”, you can find a whole lot more queries to interact with the blockchain and their mandatory and optional parameters at https://nxtwiki.org/wiki/The_Nxt_API.

As I said earlier the fee to transact is 1 NXT. 1 NXT = 100,000,000 NQT (nanoquants).
1 NQT is the smallest unit of denomination in NXT same as 1 satoshi in Bitcoin.
The Nxt Server accepts the fee in NQT, so we pay exactly 100 million NQT ($0.03)

The “broadcast” parameter can be changed to false, in this case you will receive ‘transactionBytes’ in the response, which can be broadcast to the network later using the ‘broadcastTransaction’ request. But today I have set it to ‘true’ to broadcast the transaction instantly.

Remember to urlencode() the message. I insert the filename separated from the hash with a colon into the message.

$payload = array(
"requestType" => "sendMessage",
"recipient" => $recipientID,
"secretPhrase" => urlencode($secretPhrase),
"feeNQT" => 100000000,
"deadline" => 1440,
"broadcast" => "true",
"message" => urlencode($fileName . ":" . $fileHash),
"messageIsPrunable" => "true"
);
$payload_string = "";
foreach ($payload as $key => $value) {
$payload_string .= $key . "=" . $value . "&";
}
rtrim($payload_string, "&");

Send the query to NXT server using sendRequest() function:

$output = sendRequest($host, $payload, $payload_string);

and decode the JSON response from the server to get the transaction id:

if ($output != false) {
$txId = json_decode($output)->transaction;
}

Now that there is a positive response on the accepted transaction and its ID is known, let’s update the record in the in-house db.

$lastId = $pdo->lastInsertId();
$sql = "UPDATE files SET txid = '$txId' where id = '$lastId'";
$result = $pdo->exec($sql);

We can optionally provide these links to the customer for future reference and to prove that the hash was uploaded:

echo "NXT Transaction ID: " . $txId . ",
JSON response";
echo "

Use these links to verify Sha256 hash of your file saved in our internal database against the permanent record in the NXT blockchain:

" . $fileHash;

Optionally email the customer the $txId that they can later use to verify hash or somehow else give them basic information on retrieval of the hash from in-house db and comparing it to blockchain stored hash in the future, by timestamp or other criteria.

This app doesn’t include user authentication. Normally the customer or user of an intranet service would be able to see their files after having authenticated to the site.

This app also assumes that the verification app is out of reach of the in-house database maintainer to prevent faking verification outcome.

Now the record is saved in the company’s database. Show the db record to confirm it’s there.

$sth = $pdo->prepare("SELECT id, txid, hash, uploadtime, filename FROM files ORDER BY id DESC");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
if ($result != false) {
var_dump($result);
}

The verification app

To use the hash verification app the customer must have the transaction ID in the NXT blockchain
passed to them when the transaction was submitted to the Nxt Blockchain.

Suppose the customer does have it, saved in the mail archive or retrieved by other means.
Here it is.

$txId = "111111111111111111";

Let us see what our in-house database has for the hash of the file. Fetch and save it in $hashInDb.

$pdo = new PDO('sqlite:/home/lurker10/phptutorial/files.db');
$sth = $pdo->prepare("SELECT hash FROM files where txid = '$txId'");
$sth->execute();
$result = $sth->fetch(PDO::FETCH_OBJ);
if ($result != false) {
$hashInDb = $result->hash;
}

Send a request to the NXT server and fetch all information stored in the NXT blockchain for transaction with the given ID.

$payload = array (
"requestType" => "getTransaction",
"transaction" => $txId
);
$payload_string = "";
foreach ($payload as $key => $value) {
$payload_string .= $key . "=" . $value . "&";
}
rtrim($payload_string, "&");

$output = sendRequest($host, $payload, $payload_string);

Decode the JSON response and extract the attachment field where the hash is stored.

In the first part of the app we recorded the filename separated from the hash with a colon.
Now we extract just the hash portion of the arbitrary message.

$attachmentPlainData = json_decode($output)->attachment->message;
$hashInBlockchain = explode(":", $attachmentPlainData)[1];

And compare what we have in the company’s database with what was recorded 1 year ago into the Nxt Blockchain.

if ($hashInDb == $hashInBlockchain)
echo "Hashes are identical";
else
echo "Hashes are not identical";

Next part of this series: Lottery on the Nxt Blockchain in Golang (and PHP)

NXT-crypto-developer