Add getData functionality to script

This commit is contained in:
Esteban Ordano 2014-12-30 14:29:49 -03:00
parent ea3ccb19c1
commit dc92bdd474
2 changed files with 40 additions and 0 deletions

View File

@ -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)

View File

@ -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();
});
});
});