1
0

anubis.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. //
  3. // Reference
  4. // https://github.com/TecharoHQ/anubis/blob/ecc716940e34ebe7249974f2789a99a2c7115e4e/web/js/proof-of-work.mjs
  5. //
  6. class anubis{
  7. public function __construct(){
  8. include_once "fuckhtml.php";
  9. $this->fuckhtml = new fuckhtml();
  10. }
  11. public function scrape($html){
  12. $this->fuckhtml->load($html);
  13. $script =
  14. $this->fuckhtml
  15. ->getElementById(
  16. "anubis_challenge",
  17. "script"
  18. );
  19. if($script === false){
  20. throw new Exception("Failed to scrape anubis challenge data");
  21. }
  22. $script =
  23. json_decode(
  24. $this->fuckhtml
  25. ->getTextContent(
  26. $script
  27. ),
  28. true
  29. );
  30. if($script === null){
  31. throw new Exception("Failed to decode anubis challenge data");
  32. }
  33. if(
  34. !isset($script["challenge"]) ||
  35. !isset($script["rules"]["difficulty"]) ||
  36. !is_int($script["rules"]["difficulty"]) ||
  37. !is_string($script["challenge"])
  38. ){
  39. throw new Exception("Found invalid challenge data");
  40. }
  41. return $this->rape($script["challenge"], $script["rules"]["difficulty"]);
  42. }
  43. private function is_valid_hash($hash, $difficulty){
  44. for ($i=0; $i<$difficulty; $i++) {
  45. $index = (int)floor($i / 2);
  46. $nibble = $i % 2;
  47. $byte = ord($hash[$index]);
  48. $nibble = ($byte >> ($nibble === 0 ? 4 : 0)) & 0x0f;
  49. if($nibble !== 0){
  50. return false;
  51. }
  52. }
  53. return true;
  54. }
  55. public function rape($data, $difficulty = 5){
  56. $nonce = 0;
  57. while(true){
  58. $hash_binary = hash("sha256", $data . $nonce, true);
  59. if($this->is_valid_hash($hash_binary, $difficulty)){
  60. $hash_hex = bin2hex($hash_binary);
  61. return [
  62. "response" => $hash_hex,
  63. //"data" => $data,
  64. //"difficulty" => $difficulty,
  65. "nonce" => $nonce
  66. ];
  67. }
  68. $nonce++;
  69. }
  70. }
  71. }