Bitcoin from the Command Line - Sending Bitcoin Transactions Programmatically with Javascript

Bitcoin from the Command Line – Sending Bitcoin Transactions Programmatically with Javascript



I have been playing around with Bitcoin a lot recently and it's really fun to do there are so many interesting things going on in the crypto space right now but one of the common complaints of working with Bitcoin is that it's pretty hard to get started and there's a lot of overhead to making accounts and sending any transactions programmatically so I want to show everyone a workflow that I have been using to interact with the Bitcoin blockchain from my command line using JavaScript this isn't a workflow that I would recommend for long-term storage though there isn't necessarily anything wrong with it I still would recommend Hardware wallets for any kind of long-term crypto asset storage but what I am going to show you is a good workflow for just hacking around sending money and building apps on top of Bitcoin so Bitcoin from the command line let's go okay the first thing that I'm going to do is create a new directory called Bitcoin and CD into it then I'm going to make a empty package JSON file and I'm going to install one library called bit core explorers now even though bit core explorers is just one single library it does require a bunch of other libraries underneath it and all of these libraries combined have all the functionality you could possibly need to interact with the Bitcoin blockchain that's why I like this library so much it's just it requires every dependency you would need the most important one is this one here called bit core Lib now you might be wondering what bit core is in the first place well bit core is an open source series of software libraries api's and SAS services for developing on top of Bitcoin and it's run by this Bitcoin company called bitpay and all the libraries are maintained underneath the bitpay github repository now I'm going to open a node console and I'm gonna load two variables I'm going to make a variable called bit core which requires the bit core Lib component of the library and this is just gonna have all the low-level tools for formatting Bitcoin data I'm also going to make a variable called X flow which is going to require a bit explorers and this is going to contain all the API integrations for interacting with a remote bitcoin know that bitpay is hosting and then i'm going to make one more variable called shell which is just an empty object that I can use as a global variable to write data to and we'll make the screencast go a little bit smoother now the first thing that I'm going to need to do is to create a Bitcoin address and I'm going to do that by making a brain wallet so Bitcoin private keys are 32 byte hex strings and almost any 32 byte hex string will work as a Bitcoin private key so a good way to generate these on the fly is to use a hashing algorithm like sha-256 that takes arbitrarily linked strings and converts them into 32 byte hex strings so I can make any string that I want I'm just gonna make one now that's always the coding bang Bitcoin screen pass 1 and then I'm gonna multiply that by a thousand so I have this really really big slug and then if I take the shot 256 hash of this that can be used as a private key for a Bitcoin account so the way that I could let me first save this as a variable called password and then I can generate the sha-256 hash by doing fit core crypto hash sha-256 and i need to pass in a byte buffer instead of a string into this hashing algorithm so I can do new buffer password and don't worry because all of this will be on github I'll make it just with all these commands but anyway what gets returned from this is the sha-256 hash of that large string that I made and it's in a byte buffer format now bit core does have an object format for private keys so that's nicer to work with than this byte buffer so I'm going to convert the byte buffer into the private key format but first I need to convert it into a big number so I'm gonna do bit core dot crypto DN dot from buffer and I'll pass in that thing that just got back and then this is that same hash in big number format and then I'll make a variable which is called VAR P key which is my private key and that will be equal to bit core private key and I will pass in that big number object and I should have now a private key that is the SHA hash of that large string that I made now if I want to see the address associated with that private key I can do P key to address and this one fwx thing that's returned here that actually is my Bitcoin address that is controlled by this private key now one thing to note this Bitcoin address is not actually the public key associated with the private key in the ECDSA cryptography there's actually additional manipulation that goes into it to get it into a Bitcoin address for example it converts it into something called base 58 which is a format that removes zeros and capital owes and it removes lowercase ELLs and capitalized so that it's a lot easier to look at without getting confused as what the digits are the full algorithm for converting a Bitcoin address from the key pair to the resulting address is here on the Bitcoin wiki which I'll link to but anyway we have this address now and if I wanted to for example copy this and go to a Bitcoin Explorer like block cipher live block cipher comm and type in the address we'll see that this address has already been seated with a little bit of Bitcoin which I had done beforehand right now I just have an address but no way to actually talk to the live Bitcoin network so I'm going to need to connect through one of bit pays hosted Bitcoin nodes first let me just stash this as a variable so I can use it later and then I'm going to instantiate a new instance of bit pays insight API so I'll do var insight equals new explode insight and this is what I mean by Bitcoin can kind of feel in a prize II to work with sometimes like I actually had to instantiate something called an insight API I'm pretty sure IBM is legally obligated to send me a LinkedIn message when I'm done with this but anyway if I wanted to now query the live Bitcoin network for information about that address I could do insight dot address and then pass in the address and now this will be a callback error result and this is why I have that shell object so I can just say shell dotter equals result and save the callback and then I could just query it through shell adder and I'll see that there's information about that Bitcoin address including the balance satoshis if I wanted to then you know quickly do something like shell dot add or not balance and see how much this is in the US dollars I could divide it by ten to the eighth and then multiply that by the price of Bitcoin which is currently like eleven thousand dollars per Bitcoin and I'll see that that's around one hundred seventy eight dollars that's currently in that account so something important to know about how Bitcoin works is what I mean when I say that the balance of this account is 1.6 million satoshis now Bitcoin accounts don't have balances the way you would think of a normal bank account is having a balance what it actually has is control over a series of unspent transaction outputs or UTX owes so if I go through the blockchain Explorer I'll see that for this account there were two transactions associated with it each transaction has inputs and outputs but the outputs are what specify this account and that's what gives us control over spending that money so if I wanted to send Bitcoin to someone from this account I wouldn't just like send it out of this balance what I would actually do is forward this unspent transaction output and use that as the input into a new transaction and then that changes the ut'fo from spent to unspent ut'fo is a binary state the transaction output is either spent or it's unspent it cannot be partially spent if I want to do send partial like some small amount of Bitcoin from this you TXO to someone I could specify a small amount to send them but then use myself as another output but this entire utx would be the input and then there would just be two outputs one is myself and I would generate a new UT excel and I can query this from the command line as well so if I did insight dot get unspent UT exo's passed in the address error results and then I will save the result on shell dot UT exo's and then if I did shell UT exo's I would see that there are two unspent transaction outputs associated with this address and if I want to get the balance per se of the account I would just look at summing these Satoshi's that the account controlled so you could do something like shell value PFOS that reduce no no comma I and then just returned memo plus I dot satoshis comma zero and that would give you that account balance one other thing to note also is that the unspent transaction outputs have this like kind of unique identifiers in it this like long thing : 0 well this is a way to uniquely identify any UT Excel on the Bitcoin network this hash right here is the hash of the transaction that the UT x I was associated with so if I copied this into block cipher and just pasted the transaction ID we'll see that this is the unique transaction and it had one output and that is that UT Excel so 0 would be the index in the outputs of the UT Excel because you could have a lot of UT exo's associated with each transaction but you can always uniquely identify a UT Excel by specifying the transaction and then the index of that UT Excel so this little two tuple here is a unique reference to any UT Excel so now I'm going to send this Bitcoin to a different address and I have a variable a door to that I have a new address that I generated and if we go to our blockchain Explorer we could see that this address has never been used there's no transactions associated with it first I'm going to generate a new TX object bit or dot transaction and this TX object will just slowly build up over time by adding more and more data to it until it's in the right format so first we need to decide which UT exo's we want to use as inputs into the transaction I'm actually going to use both of them so I could do TX dot from and then I think we had it on shell dot UT XO 0 would be the first UT Excel and that will add data to the transaction and we could actually look at the transaction as we're building it up by doing TX about to object and that will give us like a nice JavaScript object on that we could look at so we'll see that this TX ID and then the output index is the unique identifier for that UT exo and we have one UT x so associated with it but we obviously can add multiple UT exo's as inputs or else bitcoin you know wouldn't very well so let's do TX dot from shell UT EXO's one to add the second UT Excel and we'll look at the object and we'll see that now there are two UT X OS being referenced as input next I need to define the transaction outputs okay a couple things to note here first every transaction requires that you specify a fee for the miners in order for the transaction to get mind into the blockchain but you don't actually explicitly specify the mining fee anywhere in the protocol the fee for the miners is always implied as the difference between the sum of all Satoshi's from the UT X out inputs and the sum of all satoshis from the UT x o outputs so you need to do a little bit of math to make sure that you're leaving enough of a mining fee for your transaction to get mind if your fee is too low your TX might not ever get mind if it's too high you might be wasting money this is a serious process because if you do your math wrong and apply a large amount as a mining fee by mistake the miners will still scoop it up and you'll never get your Bitcoin back in practice this actually happens all the time hash tag welcome to crypto I'm going to use a mining fee of 50000 Satoshi's which is something like five dollars and yeah bitcoins not exactly cheap to send right now well at least not cheap compared to something like venmo but compared to the cost to do a wire transfer from a bank or the cost of shipping gold it still is pretty cheap the big core library lets you explicitly declare your fee so that it can do some sort of sanity checks for you to make sure that your numbers add up before you send your transaction so I'll do TX dot fee 50,000 and now if I look at my TX tattoo object I'll see that it does have this P field here but I still need to do my math to specify the outputs so I'll do TX dot 2 and 2 will be at or 2 and adder to the amount that I will send to it will be shell dot adder balance which is the total balance in that account minus 50 thousand and now if I look at my transaction I'll see that it does have this output of that many Satoshi's and this much specified for a fee so right here I'm sending all of my Bitcoin to this new address less the minor fee but if I only wanted to send a partial amount I could define another output that had the exact same address as myself as another output there's a handy function to do this in the bit core library called TX dot change where I could just do TX dot change adder and then that would look at the difference between what I have in the outputs and the fee and just said make a new output sending that back to me but just another thing to note it's considered good practice in the Bitcoin community to never reuse an address twice meaning that if I wanted to only send a partial amount I could create yet a new address and then send the change there so really I would need to make a new address like adder 3 and then send the change to a door 3 and then that would be the new account I used if I wanted to make another transaction the reason you do this is to help preserve anonymity on the network by not having accounts with massive amounts of transactions that are maybe easier for people to chase or trace yet another thing to note notice that this output here doesn't just send satoshis to an address it actually has a script field and we can dive into that by looking at TX dot – object dot outputs dot or the first item dot script and then we can turn this into human readable format by doing bit poor dot script and we'll see that it has this kind of op codes very similar to what you see on like the EVM for aetherium no this is something called Bitcoin script which is the scripting language on Bitcoin Bitcoin it's not just a ledger of you know accounts and balances it actually has a minimal scripting language it's a non turing-complete scripting language that specifies how the protocol should act so I'm not going to dive into it now but it is interesting to know that this is here and to read up a little bit about how the actual Bitcoin script works ok I've been until now this TX object could have been built up by anyone this is all public information on the network in order to ensure that we are the actual account holder of these UT exo's we're gonna need to sign this transaction object with our private key we can do that with TX dot sign and then pass in our private key which I had at P key and then that will sign the transaction with our private key and we can check that we did this correctly by calling TX dot serialize and if for some reason something is incorrect in this transaction this will throw an error so because it went through and serialized the transaction we know this transaction is correctly formatted and that we can send to the network one last thing to note is that there's a way to put arbitrary metadata on to Bitcoin transactions which you could do with TX dot add data and this is just a way to put a string of any kind of metadata embedded into your Bitcoin transaction I encourage you to look up some of the easter eggs on the Bitcoin network that people have embedded as metadata but I'm just going to ignore that right now finally I can actually execute this transaction by broadcasting it to the Bitcoin network so I can do that with insight broadcast and then I'll pass the TX object and the callback will take an error and then the TX ID if it's successful so I'll just shell dot error equals error and shell dot TX ID equals TX ID and I'll send that and then if I have an error it should be on Sheldon error I don't so that means that the transaction must have worked and I should have a TX ID on Shelby X ID so let's take this and look at block cipher and we'll see that this transaction has actually been picked up by the live Bitcoin network and block cipher as these things where they have confidence that this is a legit transaction and the amount of fees that them have been specified in terms of how preferential the miners will treat it and right now there are zero confirmations because we just transacted this but we can watch the transaction get mind into the blockchain and then this new account right here will have access to those funds once the transaction has been confirmed I will say for all the craziness and cryptocurrency right now there's still something pretty magical about this whole experience to me from my command line I can send money to anyone around the world instantly without permission not dealing with banking hours or national borders for fees that are way less than what Chase Bank would charge me so strap in everyone the revolution is going to be fun as always if you like these vids drop a note in the comments I really like reading them or reach out on Twitter at always be coding I'm always there anyway peace

17 thoughts on “Bitcoin from the Command Line – Sending Bitcoin Transactions Programmatically with Javascript

  1. I just wanted to say I really enjoy your videos, I try to understand as much of the subject matter as I can but most of it is still over my head but I am learning more every day, thank you.

  2. So I'm currently doing the bitcoin course offered from Princeton and your description of UTXO's is far better than anything the instructor has explained.

  3. Man, your coding knowledge is insane. I watch the Ruby scraping video all the time. Looking to get this good one day. Much continued success.

Leave a Reply

Your email address will not be published. Required fields are marked *