Spent several hours today figuring out how to interact with an ElectrumX server, and it resulted into just several lines of code. I hope this will save someone time. I will show 2 versions – for TCP and SSL connection to ElectrumX server.
Here is the TCP one:
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); |
socket_connect( $socket , "localhost" , 47001); |
$query = '{"id": "blk", "method": "blockchain.estimatefee", "params":["5"]}' ; |
socket_write( $socket , $query . "\n" ); |
socket_recv( $socket , $value , 10240, MSG_PEEK); |
$result =json_decode( $value ); |
If you prefer to connect to your server with SSL (I suppose you have a self-signed certificate), here is your code:
$context = stream_context_create(); |
stream_context_set_option( $context , 'ssl' , 'allow_self_signed' , true); |
stream_context_set_option( $context , 'ssl' , 'verify_peer_name' , false); |
$query = '{"id": "blk", "method": "blockchain.estimatefee", "params":["5"]}' ; |
if ( $socket = stream_socket_client( 'ssl://' . $host . ':' . $port , $errno , $errstr , 30, STREAM_CLIENT_CONNECT, $context ) |
fwrite( $socket , $query . "\n" ); |
$value = fread ( $socket ,10240); |
$result =json_decode( $value ); |
echo "ERROR: $errno - $errstr\n" ; |
Both scripts are doing the same. You should get something like this in the output: