Last active
January 8, 2018 09:09
-
-
Save Tristamoff/08235ecd54f2783a3ad7ea7454c44e15 to your computer and use it in GitHub Desktop.
Пример майнинга в блокчейне
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$db = new PDO('mysql:dbname=blockchain; host=localhost',"db_user","db_pass", | |
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SET NAMES utf8; | |
SET time_zone = '+00:00'; | |
SET NAMES utf8mb4; | |
DROP TABLE IF EXISTS `mining`; | |
CREATE TABLE `mining` ( | |
`id` int(11) NOT NULL AUTO_INCREMENT, | |
`hash` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, | |
`counts` int(11) NOT NULL, | |
PRIMARY KEY (`id`) | |
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include_once './config.php'; | |
include_once './mining_functions.php'; | |
//тянем hash и id последнего блока. считаем "часть" блоков | |
$last_block_data = getLastBlock(); | |
$last_hash = $last_block_data['last_hash']; | |
$last_block_id = $last_block_data['last_block_id']; | |
$part = $last_block_data['part']; | |
$start = 0; | |
if (!empty($_GET['start'])) { | |
$start = (int) $_GET['start']; | |
} | |
//перебираем по 30000 хэшей за раз | |
mining($part, $last_hash, $start, 30000); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//находим hash и id последнего блока. считаем "часть" блоков | |
function getLastBlock() { | |
global $db; | |
//для первого блока hash будет пустым и id = 0 | |
$last_hash = ''; | |
$last_block_id = 0; | |
//тянем hash и id последнего блока | |
$sql = "select * from `mining` order by id desc limit 1"; | |
$sth = $db->prepare($sql); | |
$sth->execute(); | |
$res = $sth->fetch(); | |
if (!empty($res['hash'])) { | |
$last_hash = $res['hash']; | |
$last_block_id = $res['id']; | |
} | |
// определяем к какой "части" относится блок | |
$part = (int)(($last_block_id + 10) / 10); | |
return [ | |
'last_hash' => $last_hash, | |
'last_block_id' => $last_block_id, | |
'part' => $part | |
]; | |
} | |
// перебор хэшей и проверка - удовлетворяет ли он условиям блокчейна | |
function mining($part, $last_hash, $start = 0, $limit = 30000) { | |
$finish = $start + $limit; | |
while($start < $finish) { | |
if ($part > 9) { | |
echo 'Blockchain full<br />'; | |
break; | |
} | |
$start++; | |
//формируем случайный хэш | |
$hash = generateMiningHash(); | |
//хэшируем последний хэш и свежесформированный | |
$new_hash = hash('sha256', $last_hash . $hash); | |
//проверяем - удовлетворяет ли сформированный хэш условиям блокчейна | |
$check = checkHash($new_hash, $part); | |
if ($check == true) { | |
// блок найден | |
echo 'Block found<br />'; | |
echo '$hash = ' . $hash .'<br>'; | |
echo '$new_hash = ' . $new_hash .'<br>'; | |
// сохраняем в таблицу | |
insertMinedBlock($hash, $start); | |
echo '<meta http-equiv="refresh" content="1;?start=0">'; | |
break; | |
} else { | |
//блок не найден | |
echo '<meta http-equiv="refresh" content="1;?start=' . $start . '">'; | |
} | |
} | |
echo 'Checked ' . $start . ' hashes'; | |
} | |
//создание блока | |
function insertMinedBlock($hash, $counts) { | |
global $db; | |
$sql = "insert into `mining` (`hash`, `counts`) values (:hash, :counts)"; | |
$sth = $db->prepare($sql); | |
$sth->bindValue(':hash', $hash); | |
$sth->bindValue(':counts', $counts); | |
$sth->execute(); | |
} | |
// проверка удовлетворяет ли хэш условиям блокчейна | |
function checkHash($hash, $part) { | |
// разбиваем строку на символы | |
$symbols = str_split($hash); | |
$check = true; | |
$ver = 1; | |
while ($ver <= $part) { | |
// для каждой "части" проверяем количество нужных символов | |
$ver_count = $ver; | |
foreach ($symbols as $symbol) { | |
if ($symbol == $ver) { | |
$ver_count--; | |
} | |
} | |
if ($ver_count != 0) { | |
// если все правила "части" выполнены - $check останется равным true | |
$check = false; | |
} | |
$ver++; | |
} | |
return $check; | |
} | |
//формирование рандомного хэша | |
function generateMiningHash() { | |
return hash('sha256', rand()); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
include_once './config.php'; | |
include_once './mining_functions.php'; | |
$sql = "select * from `mining` order by id asc"; | |
$sth = $db->prepare($sql); | |
$sth->execute(); | |
$res = $sth->fetchAll(); | |
$last_hash = ''; | |
foreach ($res as $block) { | |
$part = (int)(($block['id'] + 9) / 10); | |
$check_hash = hash('sha256', $last_hash . $block['hash']); | |
//проверяем - удовлетворяет ли сформированный хэш условиям блокчейна | |
$check = checkHash($check_hash, $part); | |
if ($check == true) { | |
echo 'Block ' . $block['id'].' ok<br>'; | |
} else { | |
echo 'Block ' . $block['id'].' fail<br>'; | |
} | |
//"сохраняем" в памяти хэш предыдущего блока | |
$last_hash = $block['hash']; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment