From dc92bdd474eb789f478c4ef42602c7993dfa659d Mon Sep 17 00:00:00 2001 From: Esteban Ordano Date: Tue, 30 Dec 2014 14:29:49 -0300 Subject: [PATCH] Add getData functionality to script --- lib/script/script.js | 16 ++++++++++++++++ test/script/script.js | 24 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/lib/script/script.js b/lib/script/script.js index 72ba781..8e557ef 100644 --- a/lib/script/script.js +++ b/lib/script/script.js @@ -332,6 +332,22 @@ Script.prototype.isDataOut = function() { this.chunks[1].length === this.chunks.len)); }; +/** + * Retrieve the associated data for this script. + * In the case of a pay to public key hash or P2SH, return the hash. + * In the case of a standard OP_RETURN, return the data + * @returns {Buffer} + */ +Script.prototype.getData = function() { + if (this.isDataOut() || this.isScriptHashOut()) { + return new Buffer(this.chunks[1].buf); + } + if (this.isPublicKeyHashOut()) { + return new Buffer(this.chunks[2].buf); + } + throw new Error('Unrecognized script type to get data from'); +}; + /** * @returns true if the script is only composed of data pushing * opcodes or small int opcodes (OP_0, OP_1, ..., OP_16) diff --git a/test/script/script.js b/test/script/script.js index 192ab3e..7fc66d0 100644 --- a/test/script/script.js +++ b/test/script/script.js @@ -1,7 +1,10 @@ 'use strict'; var should = require('chai').should(); +var expect = require('chai').expect; var bitcore = require('../..'); + +var BufferUtil = bitcore.util.buffer; var Script = bitcore.Script; var Opcode = bitcore.Opcode; var PublicKey = bitcore.PublicKey; @@ -566,4 +569,25 @@ describe('Script', function() { }); + describe('getData returns associated data', function() { + it('for a P2PKH address', function() { + var address = Address.fromString('1NaTVwXDDUJaXDQajoa9MqHhz4uTxtgK14'); + var script = Script.buildPublicKeyHashOut(address); + expect(BufferUtil.equal(script.getData(), address.hashBuffer)).to.be.true(); + }); + it('for a P2SH address', function() { + var address = Address.fromString('3GhtMmAbWrUf6Y8vDxn9ETB14R6V7Br3mt'); + var script = new Script(address); + expect(BufferUtil.equal(script.getData(), address.hashBuffer)).to.be.true(); + }); + it('for a standard opreturn output', function() { + expect(BufferUtil.equal(Script('OP_RETURN 1 0xFF').getData(), new Buffer([255]))).to.be.true(); + }); + it('fails if content is not recognized', function() { + expect(function() { + return Script('1 0xFF').getData(); + }).to.throw(); + }); + }); + });