bitcoinjs / bitcoinjs-lib

A javascript Bitcoin library for node.js and browsers.
MIT License
5.6k stars 2.08k forks source link

Generate wallets asynchronous? #1177

Closed thEpisode closed 5 years ago

thEpisode commented 5 years ago

Hi, this library is very nice but all your examples are synchronous, you have any way to use it asynchronous?

My code:

    let pass = _auth.crypto.spawn.seed(seed)
    let hash = _bitcoin.crypto.sha256(pass)

    const network = _bitcoin.networks.testnet
    const keyPair = _bitcoin.ECPair.fromPrivateKey(hash)
    const { address } = _bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey, network: network })

Thanks!

dcousens commented 5 years ago

setTimeout? What exactly do you need...

dabura667 commented 5 years ago

Are you trying to free up the EventLoop? If so, setTimeout(something, 0) should work.

something must be a function.

A helper function could be made like:

const assert = require('assert')
const _bitcoin = require('bitcoinjs-lib')

// this is useful
function makeAsync (fn1, ...args1) {
    return new Promise(resolve => {
        setTimeout(function() {
            (function(fn2, ...args2) {resolve(fn2(...args2))})(fn1, ...args1)
        }, 0)
    })
}

const main = async () => {
    let result1 = _bitcoin.crypto.sha256('haha')
    // <Buffer 09 0b 23 5e 9e b8 f1 97 f2 dd 92 79 37 22 2c 57 03 96 d9 71 22 2d 90 09 a9 18 9e 2b 6c c0 a2 c1>

    let result2 = await makeAsync(_bitcoin.crypto.sha256, 'haha')
    // <Buffer 09 0b 23 5e 9e b8 f1 97 f2 dd 92 79 37 22 2c 57 03 96 d9 71 22 2d 90 09 a9 18 9e 2b 6c c0 a2 c1>

    assert(result1.equals(result2), 'result1 not equal result2')
    console.log('You got here because result1 === result2 is ' + result1.equals(result2))

    const addThreeNumbers = (a,b,c) => a+b+c
    let number123 = await makeAsync(addThreeNumbers, 120, 2, 1)

    assert(number123 === 123, 'is not 123')
    console.log('You got here because number123 === 123 is ' + (number123 === 123))

}
var garbage_ = main() // run main to check if it works.

const yourStuff = async () => {
    let pass = await makeAsync(_auth.crypto.spawn.seed, seed)
    let hash = await makeAsync(_bitcoin.crypto.sha256, pass)

    const network = _bitcoin.networks.testnet
    const keyPair = await makeAsync(_bitcoin.ECPair.fromPrivateKey, hash)
    const { address } = await makeAsync(_bitcoin.payments.p2pkh, { pubkey: keyPair.publicKey, network: network })

}
dcousens commented 5 years ago

you have any way to use it asynchronous?

At this point, the answer is no. There are ways you can use them asynchronously, but, it is not part of our API.

thEpisode commented 5 years ago

@dabura667 is a nice solution meanwhile API support asynchronous solution. Thank you guys!