This was my first time doing test driven API development in Node.js and I must say, I really enjoyed it. I used to fall back on a Chrome plugin called Postman a lot before getting used to Mocha and test driven development. It was a joy to write code for a test that described what the endpoint should do before actually coding the new endpoint. It made me think more about the code I was going to write and what it should do. It also happened sometimes that there would be a total API overhaul (like the implementation of softdeletes). And, man was I glad I had written unit tests for all my endpoints when that happened!
But…wait.. won’t I lose a lot of time doing that?!?
Writing API tests for a node.js API can be a tedious job. We are dealing with a single event loop, so we need to take in account callbacks. Especially when doing API testing, callbacks can quickly become a pain point. A lot of times, checking whether requests work means triggering other requests sequentially to see if the database was updated by previous requests. This is why, after refactoring a bit of my tests, I was able to create a simple end-to-end testscript that I would just call whenever I wrote a new route. Every time with different input data specific to the route of course. I was later able to tie in APIDoc, a documentation generator that will create a frontend containing the documentation for all your endpoints. So in the end all my endpoints were not only fully tested, but also automatically documented in one go. This was very nice and saved me a lot of time.
Dependencies
Testing
We will be using Mocha as a testing framework for our Node.js API.
Mocha is great, but not perfect, so on top of it, we will include the supertest package that will provide abstraction for HTTP testing.
As I refactored my end to end tests into one single testscript, we will also need a package called partial compare that will do partial matching between test objects and actual return-objects from the api.
We will also use should to make our testing code more human readable and easier to write.
API documentation
A great library called APIdoc will take care of documenting all of the endpoints
End-to-end testing is a technique used to test whether the flow of an application right from start to finish is behaving as expected. The purpose of performing end-to-end testing is to identify system dependencies and to ensure that the data integrity is maintained between various system components and systems.
Translate this to API testing and you get:
GET an array of existing data
POST some new data
Test if the new data was posted
Change the new data using PUT
Test if the new data was changed
DELETE the new data
Test if the new data was removed
Of course this is the most simple scenario of RESTful API testing, and I know there’s some other endpoints that can be more complex (like counters, searches, etc.) But I will not elaborate on these in this post as these most of the time imply writing custom tests.
A test script that covers multiple endpoints
Because the sequence of testing is the same for all endpoints, I created a general script that will test different endpoints using the same code but different input based on the endpoint’s data. The input data will be stored in an object that will be called from an endpoint file in the ‘test/routes’ folder.
The content of the endpoint file will contain the e2e_test options object which has some options for the endpoint tests and apidoc generator.
Next to the options, a testData object contains all data needed to perform the tests. The object attributes are pretty self explanatory:
When we run mocha the end-to-end script will be called and run all tests for that endpoint. If you have specified a schemaDir and the apidoc boolean is set to true, the script will also automatically generate json schemas for the apidoc based on the testData.
Console output for a working API should be similar to:
API documentation generator
In your route files, above your endpoints, you can then add the following comment blocks:
Change them according to your endpoints of course. They will be used by the APIdoc generator to create the documentation frontend.
The apiSchema references in the comments displayed above will point at the schema jsons that are generated by the schema_generator.
The output directory can be changed in the options object in the endpoint test file as illustrated earlier.
Assuming the ./routes folder contains your api’s route files and the ./public folder is the folder that will contain the apidoc frontend, generate your api documentation by running:
These tests were run using mongoDB, which uses _id as a primary key. You might have to edit the test script to your needs a bit when you are using a different database or key/slug to perform individual GET,PUT,DELETE requests.
In the e2e_test script, basic authentication was used. You might also need to change this according to the authentication methods of your API.
This is an effort in mapping out the current ecosystem of tools and platforms that facilitate development of ‘smart contracts’ or ‘Autonomous agents’ using blockchain technologies.
Development Platforms
RSK is the first open-source smart contract platform with a 2-way peg to Bitcoin that also rewards the Bitcoin miners via merge-mining, allowing them to actively participate in the Smart Contract revolution. RSK goal is to add value and functionality to the Bitcoin ecosystem by enabling smart-contracts, near instant payments and higher-scalability.
MultiChain allows organizations to rapidly design, deploy and operate distributed ledgers
The Open Source Protocol for Creating Digital Assets On The Bitcoin Blockchain
We enable our partners to design, deploy, and operate highly scalable blockchain networks that meet the security, privacy, and compliance requirements of the financial services industry.
Stratumn’s developer tools leverage blockchain tech to offer extraordinary enhancements into all types of systems and business processes.
Blockchain Engine (BcE) is a platform designed for developers. BcE offers a suite of tools to create applications and services based off of the Emer blockchain. Not only is it simple to install, configure and integrate into any project, it’s widely available, offered in Microsoft’s Azure platform where it can be deployed on Ubuntu, in the cloud. You can manage it via JSON-RPC, a very simple protocol, and a web-interface.
Counterparty is a platform for free and open financial tools on the Bitcoin network.
Eris is free software that allows anyone to build their own secure, low-cost, run-anywhere applications using blockchain and smart contract technology.
The SAFE Network is soon to provide access to a world of exciting apps where the security of your data is put above all else. In time, downloading the free SAFE software will provide access to: messaging, apps, email, social networks, data storage, video conferencing, and much more.
Stellar is an open platform for building financial products that connect people everywhere.
Rubix is an industry leading blockchain application development team, focusing on interoperability, scalability, performance and security. Rubix supports developers in creating and deploying decentralized applications that are customized for unique industry and business needs
Blockchain platform for smart contracts and decentralized organisations
A powerful toolbox for building blockchain based applications.
CoinStack is a Blockchain-as-a-Service platform of Blocko to build decentralized services on Blockchain.
Blockchain as a Service, Coinstack
At Lisk you can develop your own blockchain apps with modern web technologies like HTML5, CSS3 and JavaScript.
Elements is an open source collaborative project where we work on a collection of experiments to more rapidly bring technical innovation to Bitcoin. Elements are features that are proposed and developed in this technical community that in arbitrary combinations can be fashioned into sidechains.
Open source code and developer sidechains for advancing Bitcoin.
Ethereum is a decentralized platform that runs smart contracts: applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third party interference.
BlockApps STRATO is a scalable Ethereum compliant platform for rapid development, deployment and management of enterprise blockchain applications. Our platform enables enterprises to develop early Proof of Concepts (PoCs) and scales all the way to full production systems.
The Hyperledger Project is a collaborative effort created to advance blockchain technology by identifying and addressing important features for a cross-industry open standard for distributed ledgers that can transform the way business transactions are conducted globally.
Over time this list / overview might grow. If you know of any tools or platforms that were not mentioned in this overview, please comment using the Disqus below, and I will add your insights to the list.
This week I was asked to create a simple web app that allows users to send bitcoins from one address to another using node.js.
After skimming through some online articles and forums I discovered Bitcore.
I also looked at an alternative called BitcoinJs
After comparing both, I decided to use bitcore as it seemed a little bit ahead of BitcoinJs and they also provide nice documentation and development resources on their website. Also, the company that open sourced Bitcore, Bitpay, is an established brand in the Bitcoin industry. BitPay is a payment processor that specializes in processing bitcoin payments and enabling merchants to accept bitcoin using a variety of website plugins and other integrations. Bitcore is their javascript library that allows developers to interface directly with the real bitcoin network.
1. Setting up the app
To kickstart my project, I looked for a suitable Yeoman generator. I had no desire setting up custom or advanced build automation for thisone. It would literally be a single page app that makes two simple API calls:
Get the transaction history of a Bitcoin address
Perform a transaction
I decided to use the ng-fullstack generator as it seemed to have all the tools I like to work with, except for sass, which I discovered later, after the project was scaffolded. For a moment I was tempted to go with the Angular 2 configuration, but again… it’s literally a 1 page app, so I just went with Angular 1.x. The generator includes a simple todo app, which is nice and it provides you some structure to work with.
After an initial UI overhaul, nothing remained of the todo app, but the UI was kept simple.
We have 4 input fields, two address verification buttons and a send button in green.
An input field for the origin address
An input field for the recipient address
An input field for the origin private key
An input field for the amount of mBTC to transact
2. Fetching transaction data
When users enter a Bitcoin address, the app sends an api request to the blockchain.info api and fetches the transaction history for the address.
You can see the output of an example request to the Blockchain.info api here
Before sending actual requests, I verify Bitcoin addresses using a simple regex on the clientside:
When the address data arrives in my angular client, I display the transaction history table with the dates, transaction results and hashes like so:
3. Creating Bitcoin transactions
To create a Bitcoin transaction, we need 4 things:
The Bitcoin address of the sender
The private key of the sender
A recipient address
The amount of Bitcoins to be sent
The information from the input boxes will be checked by a transaction model on the client side and is then sent to the wallet-service.js in the back end.
To create transactions using bitcore, we first need to install the bitcore and bitcore-explorers libraries using npm:
And reference them so we can use them:
3.1 Getting the sender’s balance
Before creating a transaction, we have to do some checks.
Firstly, we have to take in account the miner fee, which is the price we have to pay to send the transaction to the Bitcoin Blockchain.
This fee can directly influence the time it takes for a transaction to be confirmed on the blockchain.
At the moment of writing, the approximate minimum mining fee is 12,800 satoshis (0.05$). (https://bitcoinfees.21.co/)
Secondly, we need to check if the private key can sign the inputs. This is done by the bitcore library and is pretty complex, so I will not expand on this, but you can find more on signing transactions here.
So, our first check will be to see if the sender address balance can at least cover the mining fee.
The bitcore-explorers library includes insight, which is an open-source bitcoin blockchain API that will help us get information regarding our senders’ address.
To determine the balance of the sender address, we need to go over the unspent outputs of the sender.
Bitcoin works on the concept of discrete inputs and outputs not spending part of a balance. All transactions have as their input a reference to a previous unspent
output. Each transaction records one or more new outputs (which are referenced in the inputs of some future transactions). Outputs are “spent” when they are referenced
in a new transaction. Outputs can only be unspent or spent, they can’t be partially spent.
Wallet balance (or address balance) is an abstraction to help us humans and make Bitcoin more like conventional payment systems. Balances are not used at the protocol level. When the wallet indicates your confirmed balance is 1.2 BTC it is saying that the sum of the value of all unspent outputs in the blockchain which correspond to public keys it has the private key for total 1.2 BTC. In other words the wallet is computing the total value of the outputs which it can spend which requires a) the output be unspent and b) the client has the private key necessary to spend it. ~ Pieter Wuille
Using insight, we can return the array of utxos or Unspent Transaction Outputs:
The output in the terminal should be something like:
The sum of the utxos is basically the balance on the senders’ Bitcoin address, so we can now try the following:
Which, in my case, returned a balance of 105042196 satoshis:
3.2 Error handling and input validation
Let’s expand our code, create some constants for the miner fee and the transaction amount and include some error handling.
We will also make use of the bitcore Unit utility to define and convert our minerfee, transaction amount and balance variables:
I am also defining the same mining fee in the transaction model on the client side so the send button only becomes enabled once the amount entered exceeds the miner fee:
Let’s also validate the origin and recipient addresses in the backend before any api requests happen.
3.3 Creating a new transaction and serialization
This was a bit of a struggle for me at first since it was the first time I worked with the bitcore library and discovered that the error handling was a bit flaky.
Hence, I discovered the best way to get around this was to surround the transaction code with a try catch and make use of getSerializationError.
I decided to create a switch case so I could rewrite possible errors in my own language as I found 'Some inputs have not been fully signed' not very clear towards the end user.
The actual bitcore transaction takes the following inputs:
As you can see I have set the change address to the senders’ address.
Because outputs can only be unspent or spent, and not partially spent, there’s a concept of “change address” in the bitcoin ecosystem:
If an output of 10 BTC is available for me to spend, but I only need to transmit 1 BTC, I’ll create a transaction with two outputs, one with 1 BTC that I want to spend, and the other with 9 BTC to a change address, so I can spend this 9 BTC with another private key that I own
Here is a very interesting article on change addresses which explains the concept very well.
If you haven’t heard of change addresses and are involved in bitcoin transactions in any way, it’s definitely a recommended read.
3.4 Broadcasting the transaction to the blockchain
Now that our transaction has been signed and created, we can broadcast it to the blockchain. As we are not running our own bitcoin node, this will happen via the insight api.
When we put everything together, the entire transaction function looks like this:
We are done! Now we should be able to send Bitcoins using the bitcore library and node.js.
You can find code of the entire app in the following github repo:
https://github.com/jestersimpps/bitcoin-transact.
Recently, I was struggling with some Shopify products that had more than 100 variant combinations.
Shopify has a product variant limitation of 100 per product, whereas products themselves are unlimited.
To get around the limitation I wrote a little Node script that creates a unique Shopify product for every variant and links the SKU’s dynamically to option selectors in the product pages.
The script generates HTML for option boxes and javascript combination arrays. This content is then stored in the description body of the products using the Shopify-node API.
I had to simulate randomly timed API posts since somehow I was getting errors on API POST bursts. (I’ll revise the code after some more experiments)
The script creates two types of products in Shopify: ‘variants’ and ‘products’. This allows you to set custom search filters in the admin and keep the variants separate from the actual products.
One product can now have unlimited ‘variants’ (which are actually Shopify products). They are linked in the variant array that is injected in the product descriptions:
How to get going:
1. Prepare the Excel file
Add product rows in the products tab
Add the urls to the product images (Shopify will download the images from the urls and add them to your products)
Add product options in the options tab
Add the option identifiers in the option column on the product page
Generate all product variants using the VBA script in the variants page.
When adding new products/options, new variants appear in yellow
Add correct pricing to the variants
2. Using the xls2shop script
1. Add your Shopify credentials
2. Actions:
Removing all products:
Uploading product variants from Excel:
3. Add the following javascipt to the product pages in Shopify:
This will take care of passing the SKU of the product variant that was selected to the cart.
The product description that contains the variant data is injected in the product page. It contains a selector array and a variants array. The variants array contains all the possible combinations of the selectors with the corresponding product-variant SKU.
The add to cart script can be triggered as such:
Dynamic pricing upon selection change is done by setting an element id to price:
4. Finally, hide the option selectors in the collection pages