How to get UTXOs for an HD wallet?

To find all the addresses used by an HD wallet, you need to generate addresses and check whether they were used until you find a gap of n unused addresses. The problem is that bitcore-explorers doesn’t tell me if an address was used if all its outputs were spent. Can bitcore-explorers get some functionality to help with this?

Here’s a partial solution to this issue. It does a jQuery get() call to the Insight-API asking for the most recent transaction to an address. If an address has ever been used, it will return “true”. If not, it will return “false”.

function isAddressUsed(myAddress,callback) {
    var insightURL = explorers.Insight().url + '/api/addrs/' + myAddress + '/txs?from=0&to=1';
    var myAddressIsUsed = false;
    $.get(insightURL,function (data) {
        var isUsed = false;
        if (!jQuery.isEmptyObject(data) && data.totalItems > 0) {
            isUsed = true;

Then, call the function by doing something like this:

var myAddress = '1BitcoinXXXXXXXXX......';
var myAddressIsUsed;
isAddressUsed(myAddress,function(callback){myAddressIsUsed = callback;})

The biggest problem I see with this is that it is using asynchronous functions. As a result, if you want to check an address, then check the next one if the first was used, then the next one if the second was used, and so on, there needs to be something added in that waits for the callback response and then goes on. I haven’t really put a lot of thought into this yet, but it should be easy enough to improve on what I have here. This weekend I’ll think more about it and post an update. If you come up with something, please share!

Oh, I see. Calling insight directly. I was hoping bitcore-explorers could provide something.
It shouldn’t be too difficult to wrap this in another async function that keeps calling isAddressUsed until it finds one (or n) that isn’t used and return (through callback) all the addresses found.

As an aside, since I never use jQuery, I had a look at the source of explorers and I see it uses something called request through require('request'). But when I do require('request') it says it can’t find the module. Any idea why that is or how I can find that module?

Sorry for the late answer, my email notifications were disabled for some reason.

Thanks @mike for providing a solution, but I agree with @dskloet in that we should probably add this functionality to bitcore-explorers. Thanks for the feedback, I have opened an issue and we’ll implement it when we have time:

@maraoz There is a recent commit to bitcore-explorers that looks to add functionality for getting balance, totalReceived, totalSent, etc, though I haven’t been able to figure out how to get it to work (only spend a cursory amount of time trying though). To make a function “isAddressUsed” should be as easy as checking if totalReceived > 0.

Thanks for opening the issue.