aboutsummaryrefslogtreecommitdiffstats
path: root/lib/anubis.php
blob: 2bd6d90b34307c5db3a2270a5c37a105da207c96 (plain) (blame)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php

//
// Reference
// https://github.com/TecharoHQ/anubis/blob/ecc716940e34ebe7249974f2789a99a2c7115e4e/web/js/proof-of-work.mjs
//

class anubis{
	
	public function __construct(){
		
		include_once "fuckhtml.php";
		$this->fuckhtml = new fuckhtml();
	}
	
	public function scrape($html){
		
		$this->fuckhtml->load($html);
		
		$script =
			$this->fuckhtml
			->getElementById(
				"anubis_challenge",
				"script"
			);
		
		if($script === false){
			
			throw new Exception("Failed to scrape anubis challenge data");
		}
		
		$script =
			json_decode(
				$this->fuckhtml
				->getTextContent(
					$script
				),
				true
			);
		
		if($script === null){
			
			throw new Exception("Failed to decode anubis challenge data");
		}
		
		if(
			!isset($script["challenge"]) ||
			!isset($script["rules"]["difficulty"]) ||
			!is_int($script["rules"]["difficulty"]) ||
			!is_string($script["challenge"])
		){
			
			throw new Exception("Found invalid challenge data");
		}
		
		return $this->rape($script["challenge"], $script["rules"]["difficulty"]);
	}
	
	private function is_valid_hash($hash, $difficulty){
		
		for ($i=0; $i<$difficulty; $i++) {
			
			$index = (int)floor($i / 2);
			$nibble = $i % 2;
			
			$byte = ord($hash[$index]);
			$nibble = ($byte >> ($nibble === 0 ? 4 : 0)) & 0x0f;
			
			if($nibble !== 0){
				return false;
			}
		}
		
		return true;
	}
	
	public function rape($data, $difficulty = 5){
		
		$nonce = 0;
		
		while(true){
			
			$hash_binary = hash("sha256", $data . $nonce, true);
			
			if($this->is_valid_hash($hash_binary, $difficulty)){
				
				$hash_hex = bin2hex($hash_binary);
				
				return [
					"response" => $hash_hex,
					//"data" => $data,
					//"difficulty" => $difficulty,
					"nonce" => $nonce
				];
			}
			
			$nonce++;
		}
	}
}