itns-sidechain/lib/script/program.js

99 lines
2.1 KiB
JavaScript
Raw Normal View History

2016-08-24 04:08:40 -07:00
/*!
2016-08-24 04:15:03 -07:00
* program.js - program object for bcoin
2016-08-24 04:08:40 -07:00
* Copyright (c) 2014-2015, Fedor Indutny (MIT License)
2017-02-03 22:47:26 -08:00
* Copyright (c) 2014-2017, Christopher Jeffrey (MIT License).
2016-08-24 04:08:40 -07:00
* https://github.com/bcoin-org/bcoin
*/
'use strict';
2017-06-29 20:54:07 -07:00
const assert = require('assert');
const common = require('./common');
const scriptTypes = common.types;
2016-08-24 04:08:40 -07:00
/**
* Witness Program
2017-02-03 22:47:26 -08:00
* @alias module:script.Program
2016-08-24 04:08:40 -07:00
* @property {Number} version - Ranges from 0 to 16.
2017-11-16 18:44:38 -08:00
* @property {String|null} type - Null if malformed.
2016-08-24 04:08:40 -07:00
* @property {Buffer} data - The hash (for now).
*/
2017-11-16 18:44:38 -08:00
class Program {
/**
* Create a witness program.
* @constructor
* @param {Number} version
* @param {Buffer} data
*/
constructor(version, data) {
assert((version & 0xff) === version);
assert(version >= 0 && version <= 16);
assert(Buffer.isBuffer(data));
assert(data.length >= 2 && data.length <= 40);
this.version = version;
this.data = data;
}
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
/**
* Get the witness program type.
* @returns {ScriptType}
*/
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
getType() {
if (this.version === 0) {
if (this.data.length === 20)
return scriptTypes.WITNESSPUBKEYHASH;
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
if (this.data.length === 32)
return scriptTypes.WITNESSSCRIPTHASH;
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
// Fail on bad version=0
return scriptTypes.WITNESSMALFORMED;
}
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
// No interpretation of script (anyone can spend)
return scriptTypes.NONSTANDARD;
2016-08-24 04:08:40 -07:00
}
2017-11-16 18:44:38 -08:00
/**
* Test whether the program is either
* an unknown version or malformed.
* @returns {Boolean}
*/
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
isUnknown() {
const type = this.getType();
return type === scriptTypes.WITNESSMALFORMED
|| type === scriptTypes.NONSTANDARD;
}
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
/**
* Test whether the program is malformed.
* @returns {Boolean}
*/
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
isMalformed() {
return this.getType() === scriptTypes.WITNESSMALFORMED;
}
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
/**
* Inspect the program.
* @returns {String}
*/
2016-08-24 04:08:40 -07:00
2017-11-16 18:44:38 -08:00
inspect() {
const data = this.data.toString('hex');
const type = common.typesByVal[this.getType()].toLowerCase();
return `<Program: version=${this.version} data=${data} type=${type}>`;
}
}
2016-08-24 04:08:40 -07:00
/*
* Expose
*/
module.exports = Program;