diff --git a/classes/script.js b/classes/script.js index 9328f09..05eb68a 100644 --- a/classes/script.js +++ b/classes/script.js @@ -8,6 +8,7 @@ const isBuffer = require('../functions/is-buffer') const encodeASM = require('../functions/encode-asm') const decodeASM = require('../functions/decode-asm') const Address = require('./address') +const BufferWriter = require('./buffer-writer') // These WeakMap caches allow the objects themselves to maintain their immutability const SCRIPT_TO_CHUNKS_CACHE = new WeakMap() @@ -76,6 +77,17 @@ class Script { throw new Error('unsupported type') } + static concat (...scripts) { + const writer = new BufferWriter() + + for (const script of scripts) { + if (!(script instanceof Script)) throw new Error('all arguments need to be scripts') + writer.write(script.buffer) + } + + return new Script(writer.toBuffer()) + } + toString () { return this.toHex() } diff --git a/test/classes/script.js b/test/classes/script.js index 3856f7d..634b849 100644 --- a/test/classes/script.js +++ b/test/classes/script.js @@ -215,6 +215,27 @@ describe('Script', () => { }) }) + describe('concat', () => { + it('concatenates scripts', () => { + const emptyScript = new Script() + const script = new Script([1, 2]) + const script2 = new Script([4, 5]) + expect(Array.from(Script.concat().buffer)).to.deep.equal([]) + expect(Array.from(Script.concat(emptyScript).buffer)).to.deep.equal([]) + expect(Array.from(Script.concat(script).buffer)).to.deep.equal([1, 2]) + expect(Array.from(Script.concat(emptyScript, script).buffer)).to.deep.equal([1, 2]) + expect(Array.from(Script.concat(script, emptyScript).buffer)).to.deep.equal([1, 2]) + expect(Array.from(Script.concat(script, script2).buffer)).to.deep.equal([1, 2, 4, 5]) + expect(Array.from(Script.concat(script, script2, script).buffer)).to.deep.equal([1, 2, 4, 5, 1, 2]) + }) + + it('thows if any argument is not a scripts', () => { + const script = new Script([1, 2]) + expect(() => Script.concat('not a script')).to.throw('all arguments need to be scripts') + expect(() => Script.concat(script, 'not a script')).to.throw('all arguments need to be scripts') + }) + }) + describe('P2PKHLockScript', () => { describe('fromAddress', () => { it('creates', () => {