Skip to content

Commit

Permalink
Merge pull request #7 from com-chain/webhook
Browse files Browse the repository at this point in the history
Webhook
  • Loading branch information
FlorianDubath authored Dec 23, 2019
2 parents 84ecb5c + c3560fd commit 335f5bf
Show file tree
Hide file tree
Showing 6 changed files with 279 additions and 9 deletions.
71 changes: 71 additions & 0 deletions Buffer.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php
///// Cherry picked from https://github.com/Bit-Wasp/buffertools-php


class Buffer
{
protected $size;
protected $buffer; //string

public function __construct(string $byteString = '', int $byteSize = null)
{
if ($byteSize !== null) {
// Check the integer doesn't overflow its supposed size
if (strlen($byteString) > $byteSize) {
throw new \Exception('Byte string exceeds maximum size');
}
} else {
$byteSize = strlen($byteString);
}
$this->size = $byteSize;
$this->buffer = $byteString;
}

public static function hex(string $hexString = '', int $byteSize = null)
{
if (strlen($hexString) > 0 && !ctype_xdigit($hexString)) {
throw new \InvalidArgumentException('Buffer::hex: non-hex character passed');
}
$binary = pack("H*", $hexString);
return new self($binary, $byteSize);
}

public static function int($integer, $byteSize = null)
{
$hex_dec = dechex($integer);
return Buffer::hex($hex_dec, $byteSize);
}




public function getSize()
{
return $this->size;
}


public function getBinary()
{
if ($this->size !== null) {
if (strlen($this->buffer) < $this->size) {
return str_pad($this->buffer, $this->size, chr(0), STR_PAD_LEFT);
} elseif (strlen($this->buffer) > $this->size) {
return substr($this->buffer, 0, $this->size);
}
}
return $this->buffer;
}

public function getHex()
{
return unpack("H*", $this->getBinary())[1];
}


public function equals(Buffer $other)
{
return ($other->getSize() === $this->getSize()
&& $other->getBinary() === $this->getBinary());
}
}
81 changes: 81 additions & 0 deletions TestingWebhook/testWebHook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
<?php

class MyLiteDB extends SQLite3 {
function __construct() {
$this->open('./webhookMessage.db');

$sql = "CREATE TABLE IF NOT EXISTS WebHookMessage (message TEXT NOT NULL, date TEXT NOT NULL)";
$this->query($sql);
}

function __destruct() {
$this->close();
}

public function clearMessage() {
$sql ="DELETE FROM WebHookMessage";
$this->query($sql);
}

public function insertMessage($message) {
$sql ="INSERT INTO WebHookMessage(message, date) values (\"$code\", DATETIME('now') )";
$this->query($sql);
}


public function getMessages() {
$sql ="SELECT message, date FROM WebHookMessage ORDER BY date";
$ret = $this->query($sql);
$result = array();
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$sub = array("message"=>$row['message'], "date"=>$row['date']);
array_push($result,$sub);
}

return $result;
}
}

$db = new MyLiteDB();

if (isset($_GET['cleanMessage'])) {

$db->clearMessage();
}

if (isset($_POST['resources'])) {
$db->insertMessage(json_encode($_POST['resources']));
}

$address = "0x9e898bc7c13ba309a412904f07aff65a13e15d32";
$shopId = 1;
$serverName = "Lemanopolis";
$amount =0.01;
$tx_id = 'TEST_001';

echo '
<html>
<body>
<div>
To Pay: <a target="_blank" href="https://v2.cchosting.org/index.html?address='.$address.'&amount='.$amount.'&shopId='.$shopId.'&txId='.urlencode($tx_id).'&serverName='.$serverName.'"> Click</a>
</div>
<div>
List of Messages: <a href="./testWebHook.php?cleanMessage=1"> Clear Messages</a>
<table>';

$messages = $db->getMessages();
foreach ($messages as $value){
echo '<tr><td>'.$value['message'].'</td><td>'.$value['date'].'</td></tr>';
}


echo '
</tr>
</table>
</div>
</body>
</html>';



?>
4 changes: 2 additions & 2 deletions Webhook.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

$NANT_TRANSFERT = "0xa5f7c148";
$CM_TRANSFERT = "0x60ca9c4c";
$private_key_path ='../ComChain/comchainwebhook_rsa';
$private_key_path ='../ComChainKey/comchainwebhook_rsa';
$public_key_url ='https://com-chain.org/comchainwebhook_rsa.pub';


Expand Down Expand Up @@ -74,7 +74,7 @@ function sendWebhook($url, $message) {
'COMCHAIN-CERT-URL:'.$public_key_url));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_message);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$passed=true;
Expand Down
10 changes: 5 additions & 5 deletions api.php
Original file line number Diff line number Diff line change
Expand Up @@ -259,13 +259,13 @@ function sendRawTransaction($rawtx,$gethRPC){
// if so get the dest
$dest = '0x'.$rawtx.substr(110,40);
// get the sender
// TODO $sender = TransactionEcRecover($rawtx)[0];
$sender = TransactionEcRecover($rawtx)[0];

// get the amount
$amount = hexdec($rawtx.substr(150,64));
// get the balances for dest
// get the balances
$to_bal = getBalance($dest, $contract);
// TODO $from_bal = getBalance($sender, $contract);
$from_bal = getBalance($sender, $contract);
$wh_status = 1;
}

Expand All @@ -275,11 +275,11 @@ function sendRawTransaction($rawtx,$gethRPC){
// get the balances check if changes compatible the the amount
$to_bal_after = getBalance($dest, $contract);
$from_bal_after = getBalance($sender, $contract);
if ($to_bal_after - $to_bal >= $amount) { // TODO} && $from_bal - $from_bal_after >= $amount) {
if (($to_bal_after - $to_bal >= $amount) && ($from_bal - $from_bal_after >= $amount)) {
// if so : send the webhook
$message = createWebhookMessage($data['data'], $_REQUEST['serverName'],
$_REQUEST['shopId'], $_REQUEST['txId'],
"", $rawtx); // TODO ""=> $sender
$sender, $rawtx);
$res = sendWebhook($shop_url, $message);
if ($res) {
$wh_status = 3;
Expand Down
25 changes: 23 additions & 2 deletions ecrecover_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,39 @@
require_once './Keccak.php';
use kornrunner\Keccak;

require_once './Buffer.php';

function encodeLength(int $l, int $offset)
{
if ($l < 56) {
return Buffer::int($l + $offset)->getHex();
}
if ($l < 256 ** 8) {
/** @var string $bl */
$bl = Buffer::int($l)->getBinary();
return (Buffer::int(strlen($bl) + $offset + 55)->getHex()) . (Buffer::int($l)->getHex());
}
throw new \Exception('Failed to encode length');
}


function TransactionEcRecover($rawTx) {
// get the signature, last 134 chars
$len = strlen($rawTx);
$len_data = $len - 134;
$data = substr($rawTx, 0, $len_data);
$signature = substr($rawTx, $len_data);
$v = substr($signature,0,2);
$r = substr($signature,4,64);
$s = substr($signature,70,64);
$signed = '0x'.$r.$s.$v;
return ecRecoverPublic($data, $signed);

// get the rlp encoded data (change the length)
$subs = substr($rawTx, 6, $len_data-6); // 2 for the 0x + 4 for the 2 first bytes giving the length with the signature
$data_len = strlen($subs)/2;
// add the new length
$data = encodeLength($data_len,192).$subs;
$hash = keccak256WithPrefix(hex2bin($data));
return ecRecoverPublic($hash, $signed);
}


Expand Down
97 changes: 97 additions & 0 deletions requestMessages.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
<?php
require_once './Keccak.php';
require_once './ecrecover_helper.php';
use kornrunner\Keccak;

header('Access-Control-Allow-Origin: *');
/*
UseCases:
Add a reference:
POST with:
data = {'add_req'='0x123...', 'add_to'='0x123...', 'ref_to'='0x123...', 'ref_req'='0x123...'}
sign = 0x123..
Read a reference :
GET with:
add_req = 0x123..
add_to = 0x123..
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// POST case

// Check signature
$input_data = $_POST['data'];
$input_obj = json_decode($_POST['data']);

$input_sign = $_POST['sign'];
$ec_recover_result = personal_ecRecover($input_data, $input_sign);
if ($ec_recover_result !== $input_obj->{'add_req'}){
// wrong signature
exit("Bye!");
}

// insert data
$add_from = $ec_recover_result;
$add_to = preg_replace("/[^a-zA-Z0-9]+/", "", $input_obj->{'add_cli'});
$ref_from = preg_replace("/[^a-zA-Z0-9]+/", "", $input_obj->{'ref_req'});
$ref_to = preg_replace("/[^a-zA-Z0-9]+/", "", $input_obj->{'ref_cli'});


$session = getDBSession();
$query = "INSERT INTO request_reference (add_from, add_to, ref_from, ref_to) VALUES (?,?,?,?)";
$options = array('arguments' => array($add_from, $add_to, $ref_from, $ref_to));

$session->execute(new Cassandra\SimpleStatement($query), $options);
echo '{"result":"OK"}';


} else {
// GET case

// Check inputs
$addr_from = strtolower(preg_replace("/[^a-zA-Z0-9]+/", "", $_GET['add_req']));
if (strlen($addr_from) != 42) {
exit("Bye!");
}
$addr_cli = strtolower(preg_replace("/[^a-zA-Z0-9]+/", "", $_GET['add_cli']));
if (strlen($addr_cli) != 42) {
exit("Bye!");
}

// get the data from the DB
$session = getDBSession();

$query = "SELECT ref_from, ref_to FROM request_reference WHERE add_from = '$addr_from' and add_to = '$addr_cli'";


// the address is a primary key it should be only 0 or 1 row
$counter=0;
foreach ($session->execute(new Cassandra\SimpleStatement($query)) as $row) {
$string[$counter] = json_encode($row);
$counter++;
}

// Return empty object if address pait is not found
isset($string) or exit("[]");

// return the keys
echo $string[0];
}




/*
FUNCTIONS
*/

function getDBSession() {
$cluster = Cassandra::cluster('127.0.0.1') ->withCredentials("webhook_rw", "Private_access_transactions")->build();
$keyspace = 'comchain';
return $cluster->connect($keyspace);
}

?>

0 comments on commit 335f5bf

Please sign in to comment.