Bitcoin Development

I wanted to learn a bit more about Bitcoin development so I created a hello world example.

First, generate an address and get some bitcoins. Then check your balance to make sure it has been mined.

const { PrivateKey, Unit, Networks, Transaction, Script } = require('bitcore-lib');
const Message = require('bitcore-message');
const explorers = require('bitcore-explorers');

const insight = new explorers.Insight('testnet'); const miningFee = 999;

const WIF = 'cRsbEYyVB2XMBc4gSFBqdCdCWiXYjpKExqRAeGvAHW2tQXryPJwU'; const privateKey = PrivateKey.fromWIF(WIF); const publicKey = privateKey.publicKey; const address = publicKey.toAddress(Networks.testnet);

const targetPublicKey = new PrivateKey().publicKey; const targetAddress = publicKey.toAddress(Networks.testnet);

console.log('Address', address); console.log('Target Address', targetAddress);

insight.getUnspentUtxos(address, (error, utxos) => { if (error) { throw error; } else { const utxo = utxos[0].toObject(); if ((Unit.fromBTC(utxo.amount).toSatoshis() - miningFee > miningFee)) { const transaction = new Transaction(Networks.testnet) .from(utxos) .fee(miningFee) .to(targetAddress, miningFee) .change(address) .addData('Hello world') .sign(privateKey);

  console.log(`Transaction hex: ${transaction.checkedSerialize()}`);

  insight.broadcast(transaction, (error, result) => {
    if (error) {
      throw error;
    }

    console.log('result', result);
  });
} else {
  throw 'Not enough funds';
}

} });

One thing to make note of is developing a POC is awkward using bitcore. They have a built in 'security mechanism' that prevents nested npm module dependencies. I created a work around - an npm post-install script that removes dependent modules and symlinks to just one.

References