-
Notifications
You must be signed in to change notification settings - Fork 0
/
Block.php
52 lines (47 loc) · 1.11 KB
/
Block.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<?php
/**
* Created by PhpStorm.
* User: kumfo
* Date: 2018/2/24
* Time: 上午9:50
*/
class Block
{
public $hash;
public $previousHash;
private $data;
private $timeStamp;
private $nonce;
public function __construct($data,$previousHash)
{
$this->data = $data;
$this->previousHash = $previousHash;
$this->timeStamp = Time::getMsectime();
$this->hash = $this->calculateHash();
}
/**
* 计算hash值
* @return string
*/
public function calculateHash() {
$calculatedHash = StringUtil::applySha256(
$this->previousHash .
$this->timeStamp.
$this->nonce.
$this->data
);
return $calculatedHash;
}
/**
* 挖矿
* @param integer $difficulty 难度
*/
public function mineBlock($difficulty) {
$target = str_repeat('0',$difficulty);
while(mb_substr($this->hash,0,$difficulty) !== $target) {
$this->nonce ++;
$this->hash = $this->calculateHash();
}
echo "Block已挖到: " . $this->hash ."\n";
}
}