function decode_length(&$string) { $length = ord(string_shift($string)); if ($length & 0x80) { $length &= 0x7f; $temp = string_shift($string, $length); list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)); } return $length; }
function ssh1_connect($host, $port) { $identifier = 'SSH-1.5-' . basename(__FILE__); $fsock = fsockopen($host, $port, $errno, $errstr, 10); if (!$fsock) { die("Error {$errno}: {$errstr}"); } $init_line = fgets($fsock, 255); if (!preg_match('#SSH-([0-9\\.]+)-(.+)#', $init_line, $parts)) { die('Not an SSH server on the other side.'); } if ($parts[1][0] != 1) { die("SSH version {$parts[1]} is not supported!"); } echo "Connecting to {$init_line}\r\n"; fputs($fsock, "{$identifier}\n"); $packet = get_binary_packet($fsock); if ($packet['type'] != SSH_SMSG_PUBLIC_KEY) { die('Expected SSH_SMSG_PUBLIC_KEY!'); } $anti_spoofing_cookie = string_shift($packet['data'], 8); string_shift($packet['data'], 4); $temp = unpack('nlen', string_shift($packet['data'], 2)); $server_key_public_exponent = new Math_BigInteger(string_shift($packet['data'], ceil($temp['len'] / 8)), 256); $temp = unpack('nlen', string_shift($packet['data'], 2)); $server_key_public_modulus = new Math_BigInteger(string_shift($packet['data'], ceil($temp['len'] / 8)), 256); $temp = unpack('nlen', string_shift($packet['data'], 2)); $host_key_public_exponent = new Math_BigInteger(string_shift($packet['data'], ceil($temp['len'] / 8)), 256); $temp = unpack('nlen', string_shift($packet['data'], 2)); $host_key_public_modulus = new Math_BigInteger(string_shift($packet['data'], ceil($temp['len'] / 8)), 256); $session_id = pack('H*', md5($host_key_public_modulus . $server_key_public_modulus . $anti_spoofing_cookie)); // ought to use a cryptographically secure random number generator (which mt_srand is not) list($sec, $usec) = explode(' ', microtime()); mt_srand((double) $sec + (double) $usec * 100000); $session_key = ''; for ($i = 0; $i < 32; $i++) { $session_key .= chr(mt_rand(0, 255)); } $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0)); echo "starting rsa encryption\r\n\r\n"; if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) { $prepped_key = prep_session_key($double_encrypted_session_key, $server_key_public_modulus); rsa_crypt($prepped_key, array($server_key_public_exponent, $server_key_public_modulus)); rsa_crypt2($prepped_key, array($server_key_public_exponent, $server_key_public_modulus)); } else { $prepped_key = prep_session_key($double_encrypted_session_key, $host_key_public_modulus); rsa_crypt($prepped_key, array($host_key_public_exponent, $host_key_public_modulus)); rsa_crypt2($prepped_key, array($host_key_public_exponent, $host_key_public_modulus)); } }
set_time_limit(0); require_once ABSPATH . 'db_config.php'; require_once ABSPATH . 'includes/autoload.php'; require_once ABSPATH . 'includes/errors.php'; $db = new MySQLidb(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, DB_PORT); $encrypted_data = $_REQUEST['data']; //debug_print("encrypted_data={$encrypted_data}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $binary_tx_hashes = decrypt_data($encrypted_data, $db, $decrypted_key); if (substr($binary_tx_hashes, 0, 7) == '[error]') { die($binary_tx_hashes); } //debug_print("binary_tx_hashes={$binary_tx_hashes}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $binary_tx = ''; // Разбираем список транзакций do { list(, $tx_hash) = unpack("H*", string_shift($binary_tx_hashes, 16)); if (!$tx_hash) { continue; } $tx = $db->query(__FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__, "\n\t\t\tSELECT `data`\n\t\t\tFROM `" . DB_PREFIX . "transactions`\n\t\t\tWHERE `hash` = 0x{$tx_hash}\n\t\t\t", 'fetch_one'); if ($tx) { $binary_tx .= ParseData::encode_length_plus_data($tx); } } while ($binary_tx_hashes); // шифруем тр-ии $aes = new Crypt_AES(); $aes->setKey($decrypted_key); $encrypted_data = $aes->encrypt($binary_tx); unset($aes); //debug_print("decrypted_key={$decrypted_key}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); //debug_print("encrypted_data={$encrypted_data}", __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__);
// Это хэш для соревнования, у кого меньше хэш list(, $new_data['hash']) = unpack("H*", string_shift($binary_data, 32)); // Для доп. соревнования, если head_hash равны (шалит кто-то из майнеров и позже будет за такое забанен) list(, $new_data['head_hash']) = unpack("H*", string_shift($binary_data, 32)); $db->query(__FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__, "\n\t\t\t\tINSERT IGNORE INTO `" . DB_PREFIX . "queue_blocks` (\n\t\t\t\t\t`hash`,\n\t\t\t\t\t`head_hash`,\n\t\t\t\t\t`user_id`,\n\t\t\t\t\t`block_id`\n\t\t\t\t) VALUES (\n\t\t\t\t\t0x{$new_data['hash']},\n\t\t\t\t\t0x{$new_data['head_hash']},\n\t\t\t\t\t{$new_data['user_id']},\n\t\t\t\t\t{$new_data['block_id']}\n\t\t\t\t)"); //debug_print($db->printsql(), __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); } } debug_print($new_data, __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $variables = ParseData::get_variables($db, array('max_tx_size')); $need_tx = ''; // Разбираем список транзакций do { // 1 - это админские тр-ии, 0 - юзерские $new_data['high_rate'] = binary_dec(string_shift($binary_data, 1)); list(, $new_data['tx_hash']) = unpack("H*", string_shift($binary_data, 16)); // тр-ий нету if (!$new_data['tx_hash']) { debug_print('!$new_data[tx_hash]', __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); exit; } // проверим, нет ли у нас такой тр-ии $exists = $db->query(__FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__, "\n\t\t\tSELECT count(`hash`)\n\t\t\tFROM `" . DB_PREFIX . "log_transactions`\n\t\t\tWHERE `hash` = 0x{$new_data['tx_hash']}\n\t\t\t", 'fetch_one'); if ($exists) { debug_print('!exists! continue', __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); continue; } $need_tx .= hextobin($new_data['tx_hash']); } while ($binary_data); if (!$need_tx) { exit;
if ($config['first_load_blockchain'] == 'file') { debug_print('download blockchain', __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); downloadFile('http://dcoin.me/blockchain', ABSPATH . 'public/blockchain'); //file_put_contents(ABSPATH . 'public/blockchain', fopen('http://github.com/c-darwin/dcoin_blocks/raw/master/blockchain-27-08-14', 'r')); } $first = true; if (file_exists(ABSPATH . 'public/blockchain') && filesize(ABSPATH . 'public/blockchain') > 52000000) { debug_print('file_exists blockchain', __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); $fp = fopen(ABSPATH . 'public/blockchain', 'r'); do { $data_size = binary_dec(fread($fp, 5)); if ($data_size) { $data_binary = fread($fp, $data_size); $block_id = binary_dec(string_shift($data_binary, 5)); $data_length = ParseData::decode_length($data_binary); $block_data_binary = string_shift($data_binary, $data_length); $parsedata = new ParseData($block_data_binary, $db); if ($first) { $parsedata->current_version = trim(file_get_contents(ABSPATH . 'version')); $first = false; } $error = $parsedata->ParseDataFull(); if ($error) { print $error; break; } $parsedata->insert_into_blockchain(); // отметимся в БД, что мы живы. upd_deamon_time($db); // отметимся, чтобы не спровоцировать очистку таблиц upd_main_lock($db);
* */ $current_block_id = get_block_id($db); if (!$current_block_id) { die('$current_block_id'); } /* * Пробуем работать без локов * */ // пришли данные в post запросе от кого-то (другой нод или простой юзер) $new_testblock_binary = $_POST['data']; //print_R($_POST); $new_testblock['block_id'] = ParseData::binary_dec_string_shift($new_testblock_binary, 4); $new_testblock['time'] = ParseData::binary_dec_string_shift($new_testblock_binary, 4); $new_testblock['user_id'] = ParseData::binary_dec_string_shift($new_testblock_binary, 5); list(, $new_testblock['mrkl_root']) = unpack("H*", string_shift($new_testblock_binary, 32)); $sign_size = ParseData::decode_length($new_testblock_binary); $new_testblock['signature'] = ParseData::string_shift($new_testblock_binary, $sign_size); $new_testblock['signature_hex'] = bin2hex($new_testblock['signature']); debug_print("new_testblock: " . print_r_hex($new_testblock), __FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__); if (!check_input_data($new_testblock['block_id'], 'int')) { die('[error] gate_tetblock.php 1 block_id'); } if (!check_input_data($new_testblock['user_id'], 'int')) { die('[error] gate_tetblock.php user_id'); } if (!check_input_data($new_testblock['time'], 'int')) { die('[error] gate_tetblock.php time'); } if (!check_input_data($new_testblock['mrkl_root'], 'sha256')) { die('[error] gate_tetblock.php mrkl_root');
function get_end_block_id() { if (!file_exists(ABSPATH . 'public/blockchain')) { return 0; } else { $rs = fopen(ABSPATH . 'public/blockchain', 'r'); // размер блока, записанный в 5-и последних байтах файла blockchain fseek($rs, -5, SEEK_END); $size = binary_dec(fread($rs, 5)); // сам блок fseek($rs, -($size + 5), SEEK_END); $data_binary = fread($rs, $size + 5); // размер (id блока + тело блока) $data_length = binary_dec(string_shift($data_binary, 5)); $block_id = binary_dec(string_shift($data_binary, 5)); fclose($rs); return $block_id; } }
function get_prev_block($block_id) { if (!$this->prev_block) { $data = $this->db->query(__FILE__, __LINE__, __FUNCTION__, __CLASS__, __METHOD__, "\n\t\t\t\t\t\tSELECT `hash`, `head_hash`, `data`\n\t\t\t\t\t\tFROM `" . DB_PREFIX . "block_chain`\n\t\t\t\t\t\tWHERE `id` = {$block_id}\n\t\t\t\t\t\t", 'fetch_array'); $binary_data = $data['data']; string_shift($binary_data, 1); // 0 - блок, >0 - тр-ии $this->block_info = parse_block_header($binary_data); $this->block_info['hash'] = bin2hex($data['hash']); $this->block_info['head_hash'] = bin2hex($data['head_hash']); } $this->prev_block = $this->block_info; }