Class: Shugoi::ChallengeScript

Inherits:
Object
  • Object
show all
Defined in:
lib/shugoi/challenge_script.rb

Class Method Summary collapse

Class Method Details

.render(difficulty) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/shugoi/challenge_script.rb', line 3

def self.render(difficulty)
  <<~JS
    (function(){
    var P=new URLSearchParams(location.search);
    var salt=P.get('salt')||'', ts=P.get('ts')||'', nonce=P.get('nonce')||'', diff=parseInt(P.get('diff')||'#{difficulty}',10), path=P.get('path')||'/';
    if(path.charAt(0)!=='/'||path.charAt(1)==='/'||path.indexOf('\\\\')>=0)path='/';
    var enc=new TextEncoder();
    function bits(d){var l=0;for(var i=0;i<d.length;i++){var b=parseInt(d[i],16);if(b===0){l+=4;continue}l+=(b&8)?0:(b&4)?1:(b&2)?2:3;break}return l}
    var n=0;
    function step(){
      crypto.subtle.digest('SHA-256',enc.encode(salt+':'+n.toString(16))).then(function(buf){
        var h=Array.from(new Uint8Array(buf)).map(function(v){return v.toString(16).padStart(2,'0')}).join('');
        if(bits(h)>=diff){var base=path;var q=(base.indexOf('?')>=0?'&':'?')+'sg_proof='+ts+':'+nonce+':'+n.toString(16);location.replace(base+q)}
        else{n++;if(n<300000)step()}
      }).catch(function(){location.reload()});
    }
    step();
    })();
  JS
end