Blockchain By Example
上QQ阅读APP看书,第一时间看更新

Building a P2PKH script using JavaScript

The first hands-on part of this chapter will be writing a JavaScript snippet using the powerful bitcoin library bitcore-lib to build a P2PKH script (used to pay to a bitcoin address). Throughout this chapter, we will run our experiments on Ubuntu LTS 16.04.
Before you proceed with this section, make sure Node.js (nodejs.org) is installed with the latest version. Then create a directory in which we install the bitcore package:

npm install bitcore-lib --save

Let's take a look at how to build very simple script:

var bitcore = require('bitcore-lib');
var Address = bitcore.Address;
var address = Address.fromString('n3CKupfRCJ6Bnmr78mw9eyeszUSkfyHcPy');
var script = bitcore.Script.buildPublicKeyHashOut(address);
console.log(script);

The bitcore.Script object provides an interface to construct bitcoin scripts. It also gives simple interfaces to create the most common script types, such as buildPublicKeyHashOut(address), which creates a Pay-to-Public-Key-Hash (PPKH) output for the given address.

Save the code in a JavaScript file script.js and run it using node script.js. The output will show you the following ScriptPubKey script (locking script):

<Script: OP_DUP OP_HASH160 20 0xedcce89f510bf95606ec6a79cb28a745c039e220 OP_EQUALVERIFY OP_CHECKSIG>

The result is a common locking script requiring the receiver to have the private key corresponding to the public key whose Hash160 ( RIPEMD160(SHA256(publickey))) is 0xedcce89f510bf95606ec6a79cb28a745c039e220. This special hash was extracted from the receiver's bitcoin address as follows:

Bitcoin address = [Version Byte (1 byte)]+[Hash 160 of public key]+[Checksum (4 Bytes)]

This is then encoded in base 58. If the receiver provides the public key, they have to prove also their ownership of the correct private key by signing the transaction to fulfill the OP_EQUALVERIFY OP_CHECKSIG part.