From 27fbdb42ad07f9e95d1fc3d5dabfc4daf8b0e32b Mon Sep 17 00:00:00 2001 From: "Ryan X. Charles" Date: Fri, 19 Sep 2014 21:59:19 -0700 Subject: [PATCH] isOpReturn standard OP_RETURN scripts contain either just an OP_RETURN or an OP_RETURN followed by a single pushdata OP with not more than 40 bytes. --- lib/script.js | 16 ++++++++++++++++ test/script.js | 20 ++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/script.js b/lib/script.js index 18bd2b800..4b2f2aa86 100644 --- a/lib/script.js +++ b/lib/script.js @@ -137,6 +137,8 @@ Script.prototype.fromString = function(str) { throw new Error('Invalid script'); } } else if (opcodenum === Opcode.map.OP_PUSHDATA1 || opcodenum === Opcode.map.OP_PUSHDATA2 || opcodenum === Opcode.map.OP_PUSHDATA4) { + if (tokens[i + 2].slice(0, 2) != '0x') + throw new Error('Pushdata data must start with 0x'); this.chunks.push({ buf: new Buffer(tokens[i + 2].slice(2), 'hex'), len: parseInt(tokens[i + 1]), @@ -171,4 +173,18 @@ Script.prototype.toString = function() { return str.substr(0, str.length - 1); }; +Script.prototype.isOpReturn = function() { + if (this.chunks[0] === Opcode('OP_RETURN').toNumber() + && + (this.chunks.length === 1 + || + (this.chunks.length === 2 + && this.chunks[1].buf + && this.chunks[1].buf.length <= 40 + && this.chunks[1].length === this.chunks.len))) + return true; + else + return false; +}; + module.exports = Script; diff --git a/test/script.js b/test/script.js index 739f7dd0e..11f98cc0e 100644 --- a/test/script.js +++ b/test/script.js @@ -196,4 +196,24 @@ describe('Script', function() { }); + describe('#isOpReturn', function() { + + it('should know this is a (blank) OP_RETURN script', function() { + Script('OP_RETURN').isOpReturn().should.equal(true); + }); + + it('should know this is an OP_RETURN script', function() { + var buf = new Buffer(40); + buf.fill(0); + Script('OP_RETURN 40 0x' + buf.toString('hex')).isOpReturn().should.equal(true); + }); + + it('should know this is not an OP_RETURN script', function() { + var buf = new Buffer(40); + buf.fill(0); + Script('OP_CHECKMULTISIG 40 0x' + buf.toString('hex')).isOpReturn().should.equal(false); + }); + + }); + });