|
| 1 | +--- |
| 2 | +sidebar_position: 1 |
| 3 | +--- |
| 4 | +# bitcoinjs-lib |
| 5 | + |
| 6 | +sCrypt exports a submodule named `bitcoinjs-lib` which is an interface that helps you manage low-level things for the Bitcoin blockchain, such as creating key pairs, building, signing and serializing Bitcoin transactions, and more. |
| 7 | + |
| 8 | +In the context of sCrypt, the `bitcoinjs-lib` submodule is used primarily for managing key pairs and defining custom transaction builders, as demonstrated in the [How to Write a Contract](../how-to-deploy-and-call-a-contract/how-to-customize-a-contract-tx.md) section. |
| 9 | + |
| 10 | +The goal of this section is to guide you through the basics of using the `bitcoinjs-lib` submodule. |
| 11 | + |
| 12 | +## Importing |
| 13 | + |
| 14 | +You can import the `bitcoinjs-lib` submodule like this: |
| 15 | + |
| 16 | +```ts |
| 17 | +import * as bitcoinjs from '@scrypt-inc/bitcoinjs-lib' |
| 18 | +``` |
| 19 | + |
| 20 | +## Private Keys |
| 21 | + |
| 22 | + |
| 23 | +You can generate a Bitcoin private key (for `mainnet`) from a random value like this: |
| 24 | + |
| 25 | +```ts |
| 26 | +import * as ecc from '@bitcoinerlab/secp256k1'; |
| 27 | +import * as bitcoinjs from '@scrypt-inc/bitcoinjs-lib' |
| 28 | +import ECPairFactory from 'ecpair'; |
| 29 | +const ECPair = ECPairFactory(ecc); |
| 30 | +const keyPair = ECPair.makeRandom({ network: bitcoinjs.networks.bitcoin }); |
| 31 | +const wif = keyPair.toWIF(); |
| 32 | +console.log(`Private key: ${wif}`); |
| 33 | +const { address } = bitcoinjs.payments.p2pkh({ pubkey: keyPair.publicKey }); |
| 34 | +console.log(`Address: ${address}`); |
| 35 | +``` |
| 36 | + |
| 37 | +To create a private key for the test network (also referred to as `testnet`), do the following instead: |
| 38 | + |
| 39 | +```ts |
| 40 | +const keyPair = ECPair.makeRandom({ network: bitcoinjs.networks.testnet }); |
| 41 | +const wif = keyPair.toWIF(); |
| 42 | +console.log(`Private key: ${wif}`); |
| 43 | +``` |
| 44 | + |
| 45 | +The main difference between a mainnet and a testnet key is how they get serialized. |
| 46 | +Check out this [Bitcoin Wiki page on WIFs](https://en.bitcoin.it/wiki/Wallet_import_format) which explains the differences in more detail. |
| 47 | + |
| 48 | +You can also create `PrivateKey` objects from serialized keys like this: |
| 49 | + |
| 50 | +```ts |
| 51 | +const keyPair = ECPair.fromWIF('cVDFHtcTU1wn92AkvTyDbtVqyUJ1SFQTEEanAWJ288xvA7TEPDcZ'); |
| 52 | +const keyPair = ECPair.fromPrivateKey(Buffer.from('e3a9863f4c43576cdc316986ba0343826c1e0140b0156263ba6f464260456fe8', 'hex')); |
| 53 | +``` |
| 54 | + |
| 55 | +:::warning |
| 56 | +Private keys should be carefully stored and never be publicly revealed. Otherwise it may lead to loss of funds. |
| 57 | +::: |
| 58 | + |
| 59 | + |
| 60 | +## Public Keys |
| 61 | + |
| 62 | +A public key is derived from a private key and can be shared publicly. Mathematically, a public key is a point on the default elliptic curve that Bitcoin uses, named [`SECP256K1`](https://en.bitcoin.it/wiki/Secp256k1). It is the curve's base point multiplied by the value of the private key. |
| 63 | + |
| 64 | +You can get the public key corresponding to a private key the following way: |
| 65 | + |
| 66 | +```ts |
| 67 | +const keyPair = ECPair.makeRandom({ network: bitcoinjs.networks.bitcoin }); |
| 68 | +const pubKey = keyPair.publicKey |
| 69 | +``` |
| 70 | + |
| 71 | + |
| 72 | +## Addresses |
| 73 | + |
| 74 | +You can get a Bitcoin address from either the private key or the public key: |
| 75 | + |
| 76 | +```ts |
| 77 | +const keyPair = ECPair.makeRandom({ network: bitcoinjs.networks.bitcoin }); |
| 78 | +const { address } = bitcoinjs.payments.p2pkh({ pubkey: keyPair.publicKey }); |
| 79 | +console.log(`P2PKH Address: ${address}`); |
| 80 | +// Address: 19oTCSHG5o8Mdnx9cZ5f7tZ4nxSPCVTgM4 |
| 81 | +const { address } = bitcoinjs.payments.p2wpkh({ pubkey: keyPair.publicKey }); |
| 82 | +console.log(`P2WPKH Address: ${address}`); |
| 83 | +// Address: bc1qvz9qys2v0qwjhvtk8jy33p7tpffxtt797yhh5m |
| 84 | +bitcoinjs.initEccLib(ecc); |
| 85 | +const { address } = bitcoinjs.payments.p2tr({ pubkey: bitcoinjs.toXOnly(keyPair.publicKey) }); |
| 86 | +console.log(`P2TR Address: ${address}`); |
| 87 | +// Address: bc1p56rmppfnud745ml4ez654xrf6n00n0wz5jlccwjm8v6d3y6ve5tsg6zncq |
| 88 | +``` |
| 89 | + |
| 90 | +Read this [Bitcoin wiki page](https://en.bitcoin.it/wiki/Invoice_address) for more information on how Bitcoin addresses are constructed. |
| 91 | + |
| 92 | + |
| 93 | +## Constructing Transactions |
| 94 | + |
| 95 | +The `bitcoinjs-lib` submodule offers a flexible system for constructing Bitcoin transactions. Users are able to define scripts, transaction inputs and outputs, and a whole transaction including its metadata. For a complete description of Bitcoin's transaction format, please read the [Bitcoin wiki page](https://en.bitcoin.it/wiki/Transaction). |
| 96 | + |
| 97 | +As an exercise let's construct a simple [P2PKH](https://en.bitcoin.it/wiki/Transaction#Pay-to-PubkeyHash) transaction from scratch and sign it. |
| 98 | + |
| 99 | +:::note |
| 100 | +As you will notice further in these docs, most of these steps won't be needed in a regular smart contract development workflow as sCrypt already does a lot of heavy lifting for you. This section serves more as a deeper look on what is happening under the hood. |
| 101 | +::: |
| 102 | + |
| 103 | +You can create an empty psbt like this: |
| 104 | +```ts |
| 105 | +import { |
| 106 | + ExtPsbt |
| 107 | +} from '@scrypt-inc/scrypt-ts-btc' |
| 108 | +const psbt = new ExtPsbt(); |
| 109 | +``` |
| 110 | + |
| 111 | +Because the transaction will need an input that provides it with some funds, we can use the `from` function to add one that unlocks the specified [UTXO](https://en.bitcoin.it/wiki/UTXO): |
| 112 | + |
| 113 | +```ts |
| 114 | + |
| 115 | +psbt.addInput({ |
| 116 | + // if hash is string, txid, if hash is Buffer, is reversed compared to txid |
| 117 | + hash: '7d067b4a697a09d2c3cff7d4d9506c9955e93bff41bf82d439da7d030382bc3e', |
| 118 | + index: 0, |
| 119 | + sequence: 0xffffffff, // These are defaults. This line is not needed. |
| 120 | + // non-segwit inputs now require passing the whole previous tx as Buffer |
| 121 | + nonWitnessUtxo: Buffer.from(rawTxHex, 'hex') |
| 122 | +}); |
| 123 | +``` |
| 124 | + |
| 125 | +Now, the transaction needs an output that will pay to the address `mxXPxaRvFE3178Cr6KK7nrQ76gxjvBQ4UQ` in our example: |
| 126 | + |
| 127 | +```ts |
| 128 | +psbt.addOutput({ |
| 129 | + address: 'mxXPxaRvFE3178Cr6KK7nrQ76gxjvBQ4UQ', |
| 130 | + value: 80000n, |
| 131 | +}); |
| 132 | +``` |
| 133 | + |
| 134 | +Notice how the output value is 100 satoshis less than the value of the UTXO we're unlocking. This difference is the [transaction fee](https://wiki.bitcoinsv.io/index.php/Transaction_fees) (sometimes also called the "miner fee"). The transaction fees are collected by miners when they mine a block, so adding a transaction fee basically acts as an incentive for miners to include your transaction in a block. |
| 135 | + |
| 136 | +The amount of transaction fee you should pay depends on the fee rate and the bytes of the transaction. By adding an additional output to the transaction, we can control how much the transaction fee is actually paid. This output is called the change output. By adjusting the amount of change output, we can pay as little transaction fees as possible while meeting the needs of miners. |
| 137 | + |
| 138 | +You can directly call the `change` function to add a change output to the transaction without calculating the change amount by yourself. This function is smart enough that it will only add the change output when the difference between all inputs and outputs is more than the required transaction fee. |
| 139 | + |
| 140 | +```ts |
| 141 | +const feePerKb = 1; |
| 142 | +psbt.change('n4fTXc2kaKXHyaxmuH5FTKiJ8Tr4fCPHFy', feePerKb) |
| 143 | +``` |
| 144 | + |
| 145 | + |
| 146 | +### Signing |
| 147 | + |
| 148 | +Now that we have the transaction constructed, it's time to sign it. First, we need to create a Signer, so it will be ready to sign. Then we call the `signPsbt` function of the Signer. After getting signedPsbt, combine it and finalize all inputs. |
| 149 | + |
| 150 | +```ts |
| 151 | +const signer = new DefaultSigner() |
| 152 | +const signedPsbtHex = await signer.signPsbt(psbt.toHex(), psbt.psbtOptions()); |
| 153 | +const signedPsbt = psbt.combine(ExtPsbt.fromHex(signedPsbtHex)).finalizeAllInputs(); |
| 154 | +``` |
| 155 | + |
| 156 | +Viola! That's it. This will add the necessary data to the transaction's input script: the signature and the public key of our signing key. Now our transaction is ready to be posted to the blockchain. |
| 157 | + |
| 158 | +You can serialize the transaction like this: |
| 159 | + |
| 160 | +```ts |
| 161 | +const tx = signedPsbt.extractTransaction(); |
| 162 | +console.log(tx.toHex()) |
| 163 | +``` |
| 164 | + |
| 165 | +To broadcast a transaction, you can use any provider you like. |
| 166 | +For demo and test purposes you can paste the serialized transaction [here](https://mempool.space/tx/push). |
| 167 | + |
| 168 | + |
| 169 | +## References |
| 170 | + |
| 171 | +- Take a look at the full [`bitcoinjs-lib` submodule reference](../references/bitcoinjs-lib) for a full list of what functions it provides. |
| 172 | +- As the `@scrypt-inc/bitcoinjs-lib` a fork based on [bitcoinjs-lib](https://github.com/bitcoinjs/bitcoinjs-lib) implementation, take a look at their [github](https://github.com/bitcoinjs/bitcoinjs-lib). |
0 commit comments