Bitcoin UTXO


Unspent transaction outputs (UTXOs) is created when new transaction is stored in blockchain and as its name mean to, these outputs are haven't spent. To spend, UTXO is required and must fill in as input of new transaction, once new transaction stores in blockchain, this fill in UTXO will be removed from database and new UTXO will be created. From block to block, transaction to transaction, this process starts over and over again.

Blockcypher Find UTXO

<?php 

session_start();

$supportCoins = ['btc/main'=>"Bitcoin Mainnet", 'btc/test3'=>"Bitcoin Testnet3", 'dash/main'=>"Dash Mainnet", 'doge/main'=>"Dogecoin Mainnet", 'ltc/main'=>"Litecoin Mainnet",'bcy/test'=>"Blockcypher Testnet"];
$hasResult = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
	try { 
	
		if(md5($_POST['captcha']) != $_SESSION['CAPTCHA_FORM1']){
			throw new Exception("CAPTCHA verification failed.");
		} else if (!isset($supportCoins[$_POST['network']])) {
			throw new Exception('Network not found.');
		} else {
			$networkName = $_POST['network'];
		}

		$url = "https://api.blockcypher.com/v1/{$networkName}/addrs/{$_POST['address']}?unspentOnly=true&includeHex=true";
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

		$rawUtxos = curl_exec($ch);
		$rawUtxos = json_decode($rawUtxos,true);
		
		if ($rawUtxos['error']) {
			throw new Exception("URL: {$url}, Error: {$rawUtxos['error']}.");
		}
		
		$utxos = $rawUtxos['txrefs'];
		
		if (!@count($utxos)) {
			throw new Exception("UTXO not found.");
		}
		
		curl_close($ch);
		
		foreach($utxos as $k=>$utxo) {
			$url = "https://api.blockcypher.com/v1/{$networkName}/txs/{$utxo['tx_hash']}?outstart={$utxo['tx_output_n']}&instart=99999999&limit=1";

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

			$prevOutput = curl_exec($ch);
			$prevOutput = json_decode($prevOutput,true);
			
			if ($prevOutput['error']) {
				throw new Exception("URL: {$url}, Error: {$prevOutput['error']}.");
			}
		
			$prevOutput = $prevOutput['outputs'][0];
			$utxos[$k]['script'] = $prevOutput['script'];
			
			curl_close($ch);
		}

		$hasResult = true;
		
	} catch (Exception $e) {
		$errmsg .= "Problem found. " . $e->getMessage();

	}
}

include_once("html_iframe_header.php");
if ($errmsg) {
?>
	<div class="alert alert-danger">
		<strong>Error!</strong><br/><?php echo $errmsg?>
	</div>
<?php
}

if ($hasResult) {
?>
	<div class="table-responsive">
		<table border=0 class='table'>
			<tr><th>Tx Hash</th><th>Index</th><th>Script</th><th>Amount</th></tr>
			<?php
			foreach($utxos as $utxo) {
				echo "<tr><td>{$utxo['tx_hash']}</td><td>{$utxo['tx_output_n']}</td><td>{$utxo['script']}</td><td>{$utxo['value']}</td></tr>";
			}
			?>
		</table>
	</div>
<?php
}
?>
<form action='' method='post'>
	<div class="form-group">
		<label for="network">Network:</label>
		<select id="network" name="network" class="form-control" >
			<?php
			foreach($supportCoins as $k=>$v) {
				echo "<option value='{$k}'".($k == $_POST['network'] ? " selected": "").">{$v}</option>";
			}
			?>
		</select>
	</div>
	<div class="form-group">
		<label for="address">Address:</label>
		<input class="form-control" type='text' name='address' id='address' value='<?php echo $_POST['address']?>'>
	</div>
	
	<div class="form-group">
		<label for="captcha">CAPTCHA:</label>
		<img style='border:1px solid black' src='../verificationimage.php?key=CAPTCHA_FORM1'/>
		<input name="captcha" type="captcha" class="form-control" placeholder="CAPTCHA" id="captcha" value="">
	</div>

	<input type='submit' class="btn btn-success btn-block"/>
</form>
<?php 
include_once("html_iframe_footer.php");		

Electrum Find UTXO

<?php 
use BitWasp\Bitcoin\Transaction\TransactionFactory;

include_once "../common.php"; //include this just to derive $_ELECTRUM_CONFIG[...] variable
include_once "../libraries/vendor/autoload.php";

$supportCoins = ['btc/main'=>"Bitcoin Mainnet", 'btc/test'=>"Bitcoin Testnet"];
$hasResult = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
	try { 
		$postFields = [
			'id'=>'curltext',
			'method'=>'getaddressunspent',
			'params'=> [$_POST['address']]
		];
		
		$electrumRpcProtocol = "http";
		$electrumRpcHost = $_ELECTRUM_CONFIG['electrum_rpc_host'];

		if ($_POST['network'] == 'btc/test') {
			$electrumRpcPort = "7778";
			
		} else {
			$electrumRpcPort = "7777";
		}
		
		$electrumRpcUser = $_ELECTRUM_CONFIG['electrum_rpc_user'];
		$electrumRpcPwd = $_ELECTRUM_CONFIG['electrum_rpc_pwd'];
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url = "{$electrumRpcProtocol}://{$electrumRpcHost}:{$electrumRpcPort}");
		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_POST , 1);
		curl_setopt($ch, CURLOPT_USERPWD , "{$electrumRpcUser}:{$electrumRpcPwd}");
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields));

		$rawResult = curl_exec($ch);
		
		if (curl_errno($ch)) { 
			throw new Exception('CURL Error: ' . curl_error($ch). "#" . curl_errno($ch));
		} else if (!($result = json_decode($rawResult,true))) {
			throw new Exception('Invalid JSON format.');
		} else if (is_array($result['error']) AND $result['error'] !='null') {
			throw new Exception('Electrum Error: ' . $result['error']['message'] . "#" . $result['error']['code']);
		} else if (!@count($result['result'])) {
			throw new Exception("UTXO not found.");
		} else {
			
			curl_close($ch);
			
			//find utxo's scriptpubkey
			foreach($result['result'] as $k=> $utxo) {
				
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL, "{$electrumRpcProtocol}://{$electrumRpcHost}:{$electrumRpcPort}");
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
				curl_setopt($ch, CURLOPT_POST , 1);
				curl_setopt($ch, CURLOPT_USERPWD , "{$electrumRpcUser}:{$electrumRpcPwd}");
				curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
				curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['id'=>'curltext','method'=>'gettransaction','params'=> [$utxo['tx_hash']]]));

				$thisRawResult = curl_exec($ch);
		
				if (curl_errno($ch)) { 
					throw new Exception('CURL Error: ' . curl_error($ch). "#" . curl_errno($ch));
				} else if (!($thisResult = json_decode($thisRawResult,true))) {
					throw new Exception('Invalid JSON format.');
				} else if (is_array($thisResult['error']) AND $thisResult['error'] !='null') {
					throw new Exception('Electrum Error: ' . $thisResult['error']['message'] . "#" . $thisResult['error']['code']);
				} else {
					$utxhex = $thisResult['result']['hex'];
					
					$utx = TransactionFactory::fromHex($utxhex);
					$result['result'][$k]['script_pub_key'] = $utx->getOutputs()[$utxo['tx_pos']]->getScript()->getHex();
				}
				
				
				curl_close($ch);
			}
		}
		
		$hasResult = true;
		
	} catch (Exception $e) {
		$errmsg .= "Problem found. " . $e->getMessage();

	}
}

include_once("html_iframe_header.php");
if ($errmsg) {
?>
	<div class="alert alert-danger">
		<strong>Error!</strong> <?php echo $errmsg?>
	</div>
<?php
}

if ($hasResult) {
?>
	<div class="table-responsive">
		<table border=0 class='table'>
			<tr><td style='width:20%;'>Raw Electrum Result </td><td style='width:80%;'><textarea class="form-control" readonly rows=8><?php echo $rawResult;?></textarea></td></tr>
		</table>
		<table border=0 class='table'>
			
			<tr><th>Tx Hash</th><th>Index</th><th>Script</th><th>Amount</th></tr>
			<?php
			foreach($result['result'] as $utxo) {
				echo "<tr><td>{$utxo['tx_hash']}</td><td>{$utxo['tx_pos']}</td><td>{$utxo['script_pub_key']}</td><td>{$utxo['value']}</td></tr>";
			}
			?>
		</table>
	</div>
<?php
}
?>
<form action='' method='post'>
	<div class="form-group">
		<label for="network">Network:</label>
		<select id="network" name="network" class="form-control" >
			<?php
			foreach($supportCoins as $k=>$v) {
				echo "<option value='{$k}'".($k == $_POST['network'] ? " selected": "").">{$v}</option>";
			}
			?>
		</select>
	</div>
	<div class="form-group">
		<label for="address">Address:</label>
		<input class="form-control" type='text' name='address' id='address' value='<?php echo $_POST['address']?>'>
	</div>

	<input type='submit' class="btn btn-success btn-block"/>
</form>
<?php 
include_once("html_iframe_footer.php");		








Tutorials
About Us
Contents have been open source in GITHUB. Please give me a ⭐ if you found this helpful :)
Community
Problem? Raise me a new issue.
Support Us
Buy me a coffee. so i can spend more nights for this :)

BTCSCHOOLS would like to present you with more pratical but little theory throughout our tutorials. Pages' content are constantly keep reviewed to avoid mistakes, but we cannot warrant correctness of all contents. While using this site, you agree to accept our terms of use, cookie & privacy policy. Copyright 2019 by BTCSCHOOLS. All Rights Reserved.