Script().fromString(str)

...the format of fromString and toString are deliberately not compatible with
bitcoind. The format here is supposed to be both human-readable, and
byte-for-byte isomorphic to the binary representation. In the future we will
need to add support for bitcoind-like strings, both for the test data (e.g.,
script_invalid.json) or for the bitcoind console style.
This commit is contained in:
Ryan X. Charles 2014-09-01 19:42:20 -07:00
parent 6375941ef8
commit 3b2b725070
2 changed files with 51 additions and 1 deletions

View File

@ -105,6 +105,44 @@ Script.prototype.toBuffer = function() {
return bw.concat();
};
Script.prototype.fromString = function(str) {
this.chunks = [];
var tokens = str.split(' ');
var i = 0;
while (i < tokens.length) {
var token = tokens[i];
var opcode = Opcode(token);
var opcodenum = opcode.toNumber();
if (typeof opcodenum === 'undefined') {
opcodenum = parseInt(token);
if (opcodenum > 0 && opcodenum < Opcode.map.OP_PUSHDATA1) {
this.chunks.push({
buf: new Buffer(tokens[i + 1].slice(2), 'hex'),
len: opcodenum,
opcodenum: opcodenum
});
i = i + 2;
}
else {
throw new Error('Invalid script');
}
} else if (opcodenum === Opcode.map.OP_PUSHDATA1 || opcodenum === Opcode.map.OP_PUSHDATA2 || opcodenum === Opcode.map.OP_PUSHDATA4) {
this.chunks.push({
buf: new Buffer(tokens[i + 2].slice(2), 'hex'),
len: parseInt(tokens[i + 1]),
opcodenum: opcodenum
});
i = i + 3;
} else {
this.chunks.push(opcodenum);
i = i + 1;
}
}
return this;
};
Script.prototype.toString = function() {
var str = "";
@ -115,7 +153,8 @@ Script.prototype.toString = function() {
str = str + Opcode(opcodenum).toString() + " ";
} else {
var opcodenum = chunk.opcodenum;
str = str + Opcode(opcodenum).toString() + " " ;
if (opcodenum === Opcode.map.OP_PUSHDATA1 || opcodenum === Opcode.map.OP_PUSHDATA2 || opcodenum === Opcode.map.OP_PUSHDATA4)
str = str + Opcode(opcodenum).toString() + " " ;
str = str + chunk.len + " " ;
str = str + "0x" + chunk.buf.toString('hex') + " ";
}

View File

@ -151,6 +151,17 @@ describe('Script', function() {
});
describe('#fromString', function() {
it('should parse these known scripts', function() {
Script().fromString('OP_0 OP_PUSHDATA4 3 0x010203 OP_0').toString().should.equal('OP_0 OP_PUSHDATA4 3 0x010203 OP_0');
Script().fromString('OP_0 OP_PUSHDATA2 3 0x010203 OP_0').toString().should.equal('OP_0 OP_PUSHDATA2 3 0x010203 OP_0');
Script().fromString('OP_0 OP_PUSHDATA1 3 0x010203 OP_0').toString().should.equal('OP_0 OP_PUSHDATA1 3 0x010203 OP_0');
Script().fromString('OP_0 3 0x010203 OP_0').toString().should.equal('OP_0 3 0x010203 OP_0');
});
});
describe('#toString', function() {
it('should output this buffer an OP code, data, and another OP code', function() {