Commit a8154f28 authored by ketominer's avatar ketominer
Browse files

v0.0.2

parents
Pipeline #7 canceled with stages
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
# nodl-admin
<?php
/*
EasyBitcoin-PHP
A simple class for making calls to Bitcoin's API using PHP.
https://github.com/aceat64/EasyBitcoin-PHP
====================
The MIT License (MIT)
Copyright (c) 2013 Andrew LeCody
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
====================
// Initialize Bitcoin connection/object
$bitcoin = new Bitcoin('username','password');
// Optionally, you can specify a host and port.
$bitcoin = new Bitcoin('username','password','host','port');
// Defaults are:
// host = localhost
// port = 8332
// proto = http
// If you wish to make an SSL connection you can set an optional CA certificate or leave blank
// This will set the protocol to HTTPS and some CURL flags
$bitcoin->setSSL('/full/path/to/mycertificate.cert');
// Make calls to bitcoind as methods for your object. Responses are returned as an array.
// Examples:
$bitcoin->getinfo();
$bitcoin->getrawtransaction('0e3e2357e806b6cdb1f70b54c3a3a17b6714ee1f0e68bebb44a74b1efd512098',1);
$bitcoin->getblock('000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f');
// The full response (not usually needed) is stored in $this->response
// while the raw JSON is stored in $this->raw_response
// When a call fails for any reason, it will return FALSE and put the error message in $this->error
// Example:
echo $bitcoin->error;
// The HTTP status code can be found in $this->status and will either be a valid HTTP status code
// or will be 0 if cURL was unable to connect.
// Example:
echo $bitcoin->status;
*/
class Bitcoin
{
// Configuration options
private $username;
private $password;
private $proto;
private $host;
private $port;
private $url;
private $CACertificate;
// Information and debugging
public $status;
public $error;
public $raw_response;
public $response;
private $id = 0;
/**
* @param string $username
* @param string $password
* @param string $host
* @param int $port
* @param string $proto
* @param string $url
*/
public function __construct($username, $password, $host = 'localhost', $port = 8332, $url = null)
{
$this->username = $username;
$this->password = $password;
$this->host = $host;
$this->port = $port;
$this->url = $url;
// Set some defaults
$this->proto = 'http';
$this->CACertificate = null;
}
/**
* @param string|null $certificate
*/
public function setSSL($certificate = null)
{
$this->proto = 'https'; // force HTTPS
$this->CACertificate = $certificate;
}
public function __call($method, $params)
{
$this->status = null;
$this->error = null;
$this->raw_response = null;
$this->response = null;
// If no parameters are passed, this will be an empty array
$params = array_values($params);
// The ID should be unique for each call
$this->id++;
// Build the request, it's ok that params might have any empty array
$request = json_encode(array(
'method' => $method,
'params' => $params,
'id' => $this->id
));
// Build the cURL session
$curl = curl_init("{$this->proto}://{$this->host}:{$this->port}/{$this->url}");
$options = array(
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $this->username . ':' . $this->password,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $request
);
// This prevents users from getting the following warning when open_basedir is set:
// Warning: curl_setopt() [function.curl-setopt]:
// CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set
if (ini_get('open_basedir')) {
unset($options[CURLOPT_FOLLOWLOCATION]);
}
if ($this->proto == 'https') {
// If the CA Certificate was specified we change CURL to look for it
if (!empty($this->CACertificate)) {
$options[CURLOPT_CAINFO] = $this->CACertificate;
$options[CURLOPT_CAPATH] = DIRNAME($this->CACertificate);
} else {
// If not we need to assume the SSL cannot be verified
// so we set this flag to FALSE to allow the connection
$options[CURLOPT_SSL_VERIFYPEER] = false;
}
}
curl_setopt_array($curl, $options);
// Execute the request and decode to an array
$this->raw_response = curl_exec($curl);
$this->response = json_decode($this->raw_response, true);
// If the status is not 200, something is wrong
$this->status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// If there was no error, this will be an empty string
$curl_error = curl_error($curl);
curl_close($curl);
if (!empty($curl_error)) {
$this->error = $curl_error;
}
if ($this->response['error']) {
// If bitcoind returned an error, put that in $this->error
$this->error = $this->response['error']['message'];
} elseif ($this->status != 200) {
// If bitcoind didn't return a nice error message, we need to make our own
switch ($this->status) {
case 400:
$this->error = 'HTTP_BAD_REQUEST';
break;
case 401:
$this->error = 'HTTP_UNAUTHORIZED';
break;
case 403:
$this->error = 'HTTP_FORBIDDEN';
break;
case 404:
$this->error = 'HTTP_NOT_FOUND';
break;
}
}
if ($this->error) {
return false;
}
return $this->response['result'];
}
}
<?php
// Borrowed from https://gitlab.com/MMuArFF/lnd-php-wallet with added macaroon and genseed support by @ketominer
class LightningClient
{
public $macaroon = '';
function __construct($mac) {
$this->macaroon = $mac;
}
private function LnRest($add,$post= "")
{
$url = 'https://localhost:8080'.$add;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 25);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 25);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Grpc-Metadata-macaroon: '.$this->macaroon,'Accept: application/json','Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(!empty($post))
{
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $post);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
private function LnRestDEL($add)
{
$url = 'https://localhost:8080'.$add;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 25);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 25);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Grpc-Metadata-macaroon: '.$this->macaroon,'Accept: application/json','Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
public function closechannel($tx_id,$force)
{
$tx_id = explode(':',$tx_id);
($force)? $force = '?force=true': "";
$hex_id =$tx_id['0'].'/'.$tx_id['1'].$force;
$url = '/v1/channels/'.$hex_id;
$res = LightningClient::LnRestDEL($url);
return json_decode($res);
}
public function testconnect(){
$res = LightningClient::LnRest('/v1/getinfo');
if(empty($res)):
return false;
else:
return true;
endif;
}
public function getInfo() {
$res = LightningClient::LnRest('/v1/getinfo');
return json_decode($res,true);
}
public function getNodeInfos($pub_key) {
$res = LightningClient::LnRest('/v1/graph/node/'.$pub_key);
return json_decode($res,true);
}
public function testunlock () {
$info = json_decode(LightningClient::LnRest('/v1/getinfo'),true);
if(!empty($info)):
return true;
else:
return false;
endif;
}
public function unlockwallet($pass) {
$pass = json_encode(array('wallet_password' => base64_encode($pass)));
$res = LightningClient::LnRest('/v1/unlockwallet',$pass);
return json_decode($res,true);
}
public function genseed() {
$res = LightningClient::LnRest('/v1/genseed');
return json_decode($res,true);
}
public function initwallet($pass, $seed) {
$payload = json_encode(array('wallet_password' => base64_encode($pass), 'cipher_seed_mnemonic' => $seed));
$res = LightningClient::LnRest('/v1/initwallet',$payload);
return json_decode($res,true);
}
public function getWalletBalance() {
$res = LightningClient::LnRest('/v1/balance/blockchain');
return json_decode($res,true);
}
public function getChannelBalance() {
$res = LightningClient::LnRest('/v1/balance/channels');
return json_decode($res,true);
}
public function getAllchannels() {
$res = LightningClient::LnRest('/v1/channels');
return json_decode($res,true);
}
public function getPendingChannels() {
$res = LightningClient::LnRest('/v1/channels/pending');
return json_decode($res,true);
}
public function getTransactions() {
$res = LightningClient::LnRest('/v1/transactions');
return json_decode($res,true);
}
public function getPeers() {
$res = LightningClient::LnRest('/v1/peers');
return json_decode($res,true);
}
public function connectPeers($addr,$perm = false) {
$addr = explode("@",$addr);
$host = $addr[1];
$node = $addr[0];
$peers = json_encode(array(
'addr' => array ("host"=> $host,"pubkey"=>$node),
'perm'=> $perm
));
$res = LightningClient::LnRest('/v1/peers',$peers);
return json_decode($res,true);
}
public function getPendigChannels() {
$res = LightningClient::LnRest('/v1/channels/pending');
return json_decode($res,true);
}
public function getInvoices($pending_only = false) {
$res = LightningClient::LnRest('/v1/invoices');
return json_decode($res,true);
}
public function getPayments() {
$res = LightningClient::LnRest('/v1/payments');
return json_decode($res,true);
}
public function payinvoice($invoice) {
$res = LightningClient::LnRest('/v1/payreq/' . $invoice);
return json_decode($res,true);
}
public function openchannel($nodePubkeyString,$localFundingAmount,$pushSat,$targetConf = "",$satPerByte =""){
$array = json_encode(array(
'node_pubkey_string' => $nodePubkeyString,
'local_funding_amount' => $localFundingAmount,
'push_sat' => $pushSat
));
$res = LightningClient::LnRest('/v1/channels',$array);
return json_decode($res,true);
}
public function sendpayment($destination) {
$payreq = array('payment_request' => $destination);
$payreq = json_encode($payreq);
$res = LightningClient::LnRest('/v1/channels/transactions',$payreq);
return json_decode($res,true);
}
public function sendonchain($addr,$amt) {
$send = json_encode(array("addr" => $addr,
"amount" => $amt,
"target_conf"=> 0,
));
$res = LightningClient::LnRest('/v1/transactions',$send);
return json_decode($res,true);
}
public function addinvoice($value,$memo ="") {
$value = array('value'=>$value);
if(!empty($memo)): $value['memo'] = $memo; endif;
$value = json_encode($value);
$res = LightningClient::LnRest('/v1/invoices',$value);
return json_decode($res,true);
}
public function newadd($type = "") {
$res =LightningClient::LnRest('/v1/newaddress');
return json_decode($res,true);
}
}
?>
<?php
require_once('/etc/nodl/config.php');
require_once('easybitcoin.php');
require_once('easylnd.php');
$db = mysqli_connect ($db_host, $db_user, $db_pass, $db_name);
if(!$db) {
echo "Can't connect to the database";
exit(1);
}
$bitcoind['status'] = 0;
$bitcoind['chain'] = 0;
$bitcoind['height'] = 0;
$bitcoind['headers'] = 0;
$bitcoind['bestblock'] = '';
// Check batch and serial
$batch = file_get_contents('/etc/nodl/batch');
$serial = file_get_contents('/etc/nodl/serial');
$res = $db->query('SELECT name,value FROM config WHERE name=\'batch\'');
if(!$res->fetch_assoc() && $batch) {
$db->query('INSERT INTO config(name,value) VALUES(\'batch\',\''.serialize($batch).'\')');
}
$res->free_result();
$res = $db->query('SELECT name,value FROM config WHERE name=\'serial\'');
if(!$res->fetch_assoc() && $serial) {
$db->query('INSERT INTO config(name,value) VALUES(\'serial\',\''.serialize($serial).'\')');
}
$res->free_result();
// Check if there are some actions to execute
$res = $db->query('SELECT name,value FROM config WHERE name LIKE \'%_status\'');
while($row = $res->fetch_assoc()) {
switch($row['value']) {
case '100':
exec('chmod +x /usr/share/nodl/install-'.str_replace('_status','',$row['name']).'.sh');
exec('/usr/share/nodl/install-'.str_replace('_status','',$row['name']).'.sh',$values,$return);
if($return == 0) {
$return = 1;
} else {
$return = (string)(1000+$return);
}
$db->query('UPDATE config SET value=\''.$return.'\' WHERE name=\''.$row['name'].'\'');
break;
case '201':
exec('systemctl start '.str_replace('_status','',$row['name']));
$db->query('UPDATE config SET value=\'2\' WHERE name=\''.$row['name'].'\'');
break;
case '202':
exec('systemctl stop '.str_replace('_status','',$row['name']));
$db->query('UPDATE config SET value=\'1\' WHERE name=\''.$row['name'].'\'');
break;
default:
break;
}
}
$res->free_result();
// This process runs periodicaly to get status of running services and apply changes requested by admin interface
// Check if bitcoind is running
if($bitcoind_pid = exec('pgrep bitcoind')) {
$bitcoind['status'] = 1; // starting or running
$bitcoind_rpc = new Bitcoin($bitcoind_rpcuser, $bitcoind_rpcpassword, $bitcoind_rpchost, $bitcoind_rpcport);
if($bitcoind['blockchaininfo'] = $bitcoind_rpc->getblockchaininfo()) {
$bitcoind['networkinfo'] = $bitcoind_rpc->getnetworkinfo();
$bitcoind['status'] = 2; // running
if($bitcoind['blockchaininfo']['initialblockdownload'] == 1) {
$bitcoind['status'] = 10; // initial download
}
$bitcoind['chain'] = $bitcoind['blockchaininfo']['chain'];
$bitcoind['height'] = $bitcoind['blockchaininfo']['blocks'];
$bitcoind['headers'] = $bitcoind['blockchaininfo']['headers'];
$bitcoind['bestblock'] = $bitcoind['blockchaininfo']['bestblockhash'];
$bitcoind['version'] = $bitcoind['networkinfo']['version'];
$bitcoind['subversion'] = $bitcoind['networkinfo']['subversion'];
} else {
}
}
foreach($bitcoind as $name => $value) {
$name = "bitcoind_".$name;
$query = "DELETE FROM status WHERE name=?";
if(!($req = $db->prepare($query)) || !$req->bind_param("s", $name) || !$req->execute()) {
error_log("Query failed: ".$db->error);
}
$req->close();
$query = "INSERT INTO status(name,value) VALUES(?,?)";
$value = serialize($value);
if(!($req = $db->prepare($query)) || !$req->bind_param("ss", $name, $value) || !$req->execute()) {
error_log("Query failed: ".$db->error);
}
$req->close();
}
$tor['status'] = 0;
if($tor_pid = exec('pgrep tor')) {
$tor['status'] = 2;
}
foreach($tor as $name => $value) {
$name = "tor_".$name;
$query = "DELETE FROM status WHERE name=?";
if(!($req = $db->prepare($query)) || !$req->bind_param("s", $name) || !$req->execute()) {
error_log("Query failed: ".$db->error);
}
$req->close();
$query = "INSERT INTO status(name,value) VALUES(?,?)";
//if(is_array($value)) {
$value = serialize($value);
//}
if(!($req = $db->prepare($query)) || !$req->bind_param("ss", $name, $value) || !$req->execute()) {
error_log("Query failed: ".$db->error);
}
$req->close();
}
$lnd['status'] = 0;
//$lnd['chain'] = 0;
//$lnd['height'] = 0;
//$lnd['headers'] = 0;
//$lnd['bestblock'] = '';
// lnd - TODO: check if installed
if($lnd_pid = exec('pgrep lnd')) {
$lnd['status'] = 1; // starting or running
$macaroon = bin2hex(file_get_contents($lnd_macaroon));
$lnd_rpc = New LightningClient($macaroon);
$con = $lnd_rpc->testconnect();
if(!$con) { // some weird state
} else {
$lnd['getinfo'] = $lnd_rpc->getInfo();
if(isset($lnd['getinfo']['block_height'])) {
$lnd['height'] = $lnd['getinfo']['block_height'];
}
if(isset($lnd['getinfo']['version'])) {
$lnd['version'] = $lnd['getinfo']['version'];
}
if(isset($lnd['getinfo']['best_header_timestamp'])) {
$lnd['best_header_timestamp'] = $lnd['getinfo']['best_header_timestamp'];
}
if(!isset($lnd['getinfo']['synced_to_chain'])) {
$lnd['unlock'] = $lnd_rpc->testunlock();
if($lnd['unlock']=='1') {
$lnd['status'] = 10; // unlocked but not synced
} else {
$lnd['status'] = 11; // locked or not initialized