Problem with Buffer when trying to add a string to a script


#1

I am trying to add a string to a script. But I am getting this error message.

“TypeError: Buffer is not a constructor
redeamScript.add(new Buffer(base58String, “hex”));”

I have tacken this straight out of the Bitcore documentation:


section: Custom Scripts
The Bitcore documentation example:

.add(new Buffer('bacacafe', 'hex')) // add a data buffer (will append the size of the push operation first)

The code I have written trying to create some scripts is below. I appreate any help with this.
Thank you

<!DOCTYPE html>
<html>
<body>
    <script src="bitcore/bitcore.min.js"></script>
    <script>
        
        var bitcore = require('bitcore');
        bitcore.Script = require('bitcore').Script;
        bitcore.Buffer = require('bitcore').Buffer;        
        
        var base58String = "87Pmu6Sh7L8AGg7Ee3dn";
        var lockingScript = "";
        var unlockingScript = "";
        
        createScripts();
        
        //create script using bitcore
        function createScripts(){
            
            var Buffer = require('bitcore').Buffer;
            var Script = require('bitcore').Script;

            //create redeam script
            var redeamScript = new Script();
            redeamScript.add(new Buffer(base58String, "hex"));
            redeamScript.add("OP_EQUAL");

            //create locking script
            lockingScript = redeamScript.toScriptHashOut();

            //create unlocking script
            unlockingScript = new Script();            
            unlockingScript.add(new Buffer(base58String, "hex"));
            unlockingScript.add(redeamScript);
            
            //verify unlocking and locking script
            var verified = bitcore.Script.Interpreter().verify(unlockingScriptBitcore, lockingScriptBitcore);
            
        }
        
    </script>
</body>
</html>

(esteban) #2

Try using new bitcore.deps.Buffer(...) instead of new Buffer() as Buffer is not a browser standard.


#3

Thanks that works to get buffer going but now I get this error:

"Error: Invalid hex string
…arseInt(t.substr(2*o,2),16);if(isNaN(a))throw new Error(“Invalid hex string”);e[…"
bitcore.min.js (line5, col 13698)


(esteban) #4

Make sure you’re not feeding it an invalid hex string. Quick check: does it match the regex /([a-fA-F0-9][a-fA-F0-9])*/? (make sure its hexa and it’s an even amount of chars).


#5

Thanks for your help. I was wanting to pass a string in as an argument instead of a hex so removing the second argument of hex worked.

Here is how it works for me passing in a string:

redeamScript.add(new bitcore.deps.Buffer("87Pmu6Sh7L8AGg7Ee3dn OP_EQUAL"));