0% found this document useful (0 votes)
45 views5 pages

Blockchain App Devlp

The document outlines the process of developing a blockchain application that interacts with the Bitcoin blockchain using the Block Explorer API. It details the roles of the application code, Block Explorer API, and blockchain nodes, along with step-by-step instructions for setting up a Node.js environment, generating key pairs, preparing and signing Bitcoin transactions, and broadcasting them to the network. Additionally, it includes practice questions for further understanding of the concepts presented.

Uploaded by

UTKARSH SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views5 pages

Blockchain App Devlp

The document outlines the process of developing a blockchain application that interacts with the Bitcoin blockchain using the Block Explorer API. It details the roles of the application code, Block Explorer API, and blockchain nodes, along with step-by-step instructions for setting up a Node.js environment, generating key pairs, preparing and signing Bitcoin transactions, and broadcasting them to the network. Additionally, it includes practice questions for further understanding of the concepts presented.

Uploaded by

UTKARSH SINGH
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Module-V Blockchain Application Development

Blockchain Application Development


Interacting with the Bitcoin Blockchain Block Explorer API

Figure: Application interacting with the Bitcoin blockchain using the Block Explorer API

The diagram illustrates how an application interacts with the Bitcoin blockchain through a Block Explorer
API. Here's a breakdown:

1. Application Code:
o The application code is responsible for performing operations like retrieving blockchain
data, monitoring transactions, or fetching wallet balances.
o It does not directly interact with the blockchain nodes but uses the Block Explorer API as an
intermediary.
2. Block Explorer API:
o The Block Explorer API provides a standardized way to query data from the blockchain.
o This API connects to a specific blockchain node (Node 1 in this diagram) to fetch or push
data.
o Examples of queries include:
 Fetching block details.
 Retrieving transaction history.
 Checking wallet balances.
3. Node 1:
o Node 1 is a blockchain node directly connected to the application through the API.
o It is part of the larger blockchain network and interacts with other nodes to maintain a
consistent and up-to-date ledger.
4. Blockchain Network:
o The blockchain network consists of multiple interconnected nodes (Node 2, Node 3, Node 4,
and Node 5 in this case).
o These nodes share information, validate transactions, and reach consensus on the blockchain
state.
5. Communication Flow:
o The application sends requests via the Block Explorer API to Node 1.
o Node 1 retrieves the necessary information (e.g., transaction data or block details) by
communicating with other nodes in the network as needed.
o Once the information is retrieved, it is sent back to the application through the API.

In summary, the Block Explorer API acts as a bridge between the application and the Bitcoin blockchain,
abstracting the complexity of directly interacting with the network nodes.

ABHISHEK K L Assistant Professor Department of AIML


Module-V Blockchain Application Development

npm init –y //initialize node.js

npm install bitcoinjs-lib axios ecpair tiny-secp256k1 // install packages

1. Setup and initialize the bitcoinjs library in a node.js application

npm init –y //initialize node.js


npm install bitcoinjs-lib axios ecpair tiny-secp256k1 // install packages

Create a file index.js and write the following code

const bitcoin = require('bitcoinjs-lib');


const ecc = require('tiny-secp256k1');
const { ECPairFactory } = require('ecpair');

// Initialize ECPair with the ecc module


const ECPair = ECPairFactory(ecc);

// Define the network (use bitcoin.networks.testnet for testnet)


const network = bitcoin.networks.testnet;

2. Create Key Pairs for the Sender and Receiver


// Function to generate keys for Alice and Bob
const getKeys = () => {
// Generate Alice's key pair
const aliceKeys = ECPair.makeRandom({ network });
const alicePublicKey = Buffer.from(aliceKeys.publicKey); // Ensure it's a Buffer
const aliceAddress = bitcoin.payments.p2pkh({
pubkey: alicePublicKey,
network,
}).address;
const alicePrivateKey = aliceKeys.toWIF();

// Generate Bob's key pair


const bobKeys = ECPair.makeRandom({ network });
const bobPublicKey = Buffer.from(bobKeys.publicKey); // Ensure it's a Buffer
const bobAddress = bitcoin.payments.p2pkh({
pubkey: bobPublicKey,
network,
}).address;
const bobPrivateKey = bobKeys.toWIF();

console.log("Alice's Address:", aliceAddress);


console.log("Alice's Private Key:", alicePrivateKey);
console.log("Bob's Address:", bobAddress);
console.log("Bob's Private Key:", bobPrivateKey);
};
// Call the function to generate and log keys
getKeys();

ABHISHEK K L Assistant Professor Department of AIML


Module-V Blockchain Application Development

Output:
Alice's Address: mqdofsXHpePPGBFXuwwypAqCcXi48Xhb2f
Alice's Private Key: cRzjwUr4Ak7cLk5zL6mSmTSL8u7sKKn7pj9Dj9SkcZ3XxFiUVtk9
Bob's Address: mqEmVRFSnN2Gsb13EY9m4A5BeUFG6Sqtzy
Bob's Private Key: cV6Hn3Zx1QW3R7rZ1KrBR4nB8AUXFChhYGUpeWDC7rfSQFqNzXqs

3. Get Test Bitcoins in the Sender’s Wallet


Visit a Bitcoin Testnet Faucet, such as:
https://coinfaucet.eu/en/btc-testnet/
https://bitcoinfaucet.uo1.net/
https://testnet-faucet.mempool.co/

Enter the Sender Address generated in the previous step and request test bitcoins.
Check the Wallet for the Deposit:
 After a few seconds to a minute, your testnet Bitcoin should arrive at Alice's (or Bob's) wallet.
 You can check the balance by running a block explorer that supports Bitcoin testnet, like:
https://blockchair.com/bitcoin-testnet
https://live.blockcypher.com/btc-testnet/

You can search for the address there, and it will show you the transaction history and balance.

4. Get the Sender’s Unspent Outputs


var getOutputs = function () {
var url = blockExplorerTestnetApiEndpoint
+ 'addr/' + msDkUzzd69idLLGCkDFDjVRz44jHcV3pW2
+ '/utxo';
return new Promise(function (resolve, reject) {
request.get(url, function (err, res, body) {
if (err) {
reject(err);
}
resolve(body);
});
});
};
getUTXOs(address);

To get the unspent outputs, we will send an HTTP request to the UTXO endpoint with Bob’s address

Sample Output:
No UTXOs found for this address.

5. Prepare Bitcoin Transaction

const psbt = new bitcoin.Psbt({ network });

(async () => {
const utxos = await getUTXOs(senderAddress);

ABHISHEK K L Assistant Professor Department of AIML


Module-V Blockchain Application Development

const utxo = utxos[0];


psbt.addInput({
hash: utxo.txid,
index: utxo.vout,
nonWitnessUtxo:
Buffer.from(awaitaxios.get(`https://blockstream.info/testnet/api/tx/${utxo.txid}/hex`).then(res => res.data), 'hex'),
});

psbt.addOutput({
address: receiverAddress,
value: 50000, // Send 0.0005 BTC
});

psbt.addOutput({
address: senderAddress,
value: utxo.value - 50000 - 10000, // Change amount after deducting output and fee
});

console.log("Transaction prepared.");
})();

Sample Output:

Transaction prepared.

6. Sign Transaction Inputs


(async () => {
psbt.signInput(0, senderKey);

if (!psbt.validateSignaturesOfInput(0)) {
throw new Error("Signature validation failed.");
}

psbt.finalizeAllInputs();
console.log("Transaction inputs signed.");
})();

Sample Output:
Transaction inputs signed.

7. Create Transaction Hex


(async () => {
const rawTx = psbt.extractTransaction().toHex();
console.log("Raw Transaction Hex:", rawTx);
})();

Sample Output:
Raw Transaction Hex: 020000000001...

ABHISHEK K L Assistant Professor Department of AIML


Module-V Blockchain Application Development

8. Broadcast Transaction to the Network


(async () => {
const rawTx = psbt.extractTransaction().toHex();
const response = await axios.post('https://blockstream.info/testnet/api/tx', rawTx);
console.log("Transaction broadcasted. TXID:", response.data);
})();

Sample Output:
Transaction broadcasted. TXID: abcd1234...

Practice Questions
1. Explain how Application interacting with the Bitcoin blockchain using the Block Explorer API with neat
diagram..
2. With code snippet explain how to prepare bitcoin transaction and how to sign transaction inputs.
3. Explain the process of create key pairs for the sender and receiver in bitcoin.
4. With code snippet explain how to broadcast bitcoin transaction to the network.

ABHISHEK K L Assistant Professor Department of AIML

You might also like