0

I want to create a script that will take a string from a html form, add it to a txt file stored online, then compute sha256 from the sum and check if the hash starts from two zeros. I wrote a simple program, but don't know if I'm doing it right. I can't find any mistakes.

    <form onsubmit= check()>
        <label for="try">Write your answer.</label><br>
        <input type="text" id="try" name="try"><br>
        <input type="submit" value="Send">
    </form>
    <p id="return"></p>
<script>
    function read(textFile){
        var xhr=new XMLHttpRequest;
        xhr.open('GET',textFile);
        xhr.onload = function(){
            var blockchain = xhr.response;
        }
        xhr.send()
    }
    
    function check(){
        read('blockchain.txt');
        document.getElementById("try") = new string(input);
        var whole = blockchain + input;
        var hash = sha256(whole);
        if(hash.substring(2)=='00'){
            document.getElementById("return") = "congratulations!";
        }
        else{
            document.getElementById("return") = "Try again.";
        }
    }
    
    async function sha256(message) {
        const msgBuffer = new TextEncoder('utf-8').encode(message);
        const hashBuffer = await window.crypto.subtle.digest('SHA-256', msgBuffer);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
        console.log(hashHex);
        return hashHex;
    }
    
</script>
  • `var whole = blockchain + input;` - I very much doubt that `blockchain` will contain anything but `undefined` at this point. Inside your XHR load callback, you made this a _local_ variable, by using the `var` keyword. – CBroe Apr 12 '21 at 09:11
  • And even if you made it a global variable instead, you’d still not be handling the asynchronous nature of the XHR request correctly. https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – CBroe Apr 12 '21 at 09:12
  • Is there a way to make xhr request synchronous? – aciddioxide Apr 12 '21 at 09:17
  • Yes, but browsers will start blocking those in the future - so that is rather a “don’t even ask” at this point :-) Learn to “handle async” correctly, everything else does not make much sense to begin with these days. – CBroe Apr 12 '21 at 09:19
  • That's what I'll do. Thank you for help :)) – aciddioxide Apr 12 '21 at 09:23

0 Answers0