Skip to content

Instantly share code, notes, and snippets.

@Tristamoff
Created January 6, 2018 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tristamoff/8999afcef2888227b76eb3be9504513f to your computer and use it in GitHub Desktop.
Save Tristamoff/8999afcef2888227b76eb3be9504513f to your computer and use it in GitHub Desktop.
Пример блокчейна
SET NAMES utf8;
SET time_zone = '+00:00';
SET NAMES utf8mb4;
DROP TABLE IF EXISTS `blocks`;
CREATE TABLE `blocks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`author` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`data` text COLLATE utf8mb4_unicode_ci NOT NULL,
`timestamp` int(11) NOT NULL,
`hash` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
<?php
$db = new PDO('mysql:dbname=blockchain; host=localhost',"db_user","db_pass",
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
<?php
include_once './config.php';
include_once './functions.php';
// генерируем данные для записи в блок
$data = getRandomData();
// получаем хэш последнего блока
$last_hash = getLastHash();
// формируем хэш нового блока
$block_hash = createBlockHash($data['author'], $data['data'], $data['timestamp'], $last_hash);
//сохраняем блок
$new_block_id = insertNewBlock($data['author'], $data['data'], $data['timestamp'], $block_hash);
if (!empty($new_block_id)) {
echo 'Block ' . $new_block_id . ' created';
} else {
echo 'Block creation error';
}
<?php
//формируем случайные данные для наполнения блока
function getRandomData() {
$authors = ['bob', 'jack', 'tom', 'jane', 'rose', 'liam', 'hugo', 'amber', 'faith', 'zara', 'alex', 'jude'];
shuffle($authors);
$author = $authors[0];
$data = json_encode(['data' => 'Random string ' . strrev($authors[5]), 'custom_data' => 'Random number ' . rand()]);
$timestamp = time();
return [
'author' => $author,
'data' => $data,
'timestamp' => $timestamp,
];
}
//находим хэш последнего блока
function getLastHash() {
global $db;
//для первого блока хэш будет пустым
$last_hash = '';
//тянем hash последней записи
$sql = "select hash from `blocks` order by id desc limit 1";
$sth = $db->prepare($sql);
$sth->execute();
$res = $sth->fetch();
if (!empty($res['hash'])) {
$last_hash = $res['hash'];
}
return $last_hash;
}
//формирование хэша блока
function createBlockHash($author, $data, $timestamp, $last_hash) {
// формируем хэш блока, исходя из автора, данных, времени и хэша предыдущего блока
$block_hash = hash('sha256', json_encode([$author, $data, (int) $timestamp, $last_hash]));
return $block_hash;
}
//создание блока
function insertNewBlock($author, $data, $timestamp, $block_hash) {
global $db;
$sql = "insert into `blocks` (`author`, `data`, `timestamp`, `hash`) values (:author, :data, :timestamp, :hash)";
$sth = $db->prepare($sql);
$sth->bindValue(':author', $author);
$sth->bindValue(':data', $data);
$sth->bindValue(':timestamp', $timestamp);
$sth->bindValue(':hash', $block_hash);
$sth->execute();
$id = $db->lastInsertId();
return $id;
}
<?php
include_once './config.php';
include_once './functions.php';
$sql = "select * from `blocks` order by id asc";
$sth = $db->prepare($sql);
$sth->execute();
$res = $sth->fetchAll();
$last_hash = '';
foreach ($res as $block) {
// пересчитываем хэш блока
$block_hash = createBlockHash($block['author'], $block['data'], $block['timestamp'], $last_hash);
//сравниваем сформированный хэш с хэшом блока в блокчейне(БД)
if ($block_hash == $block['hash']) {
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