All files / lib/primitives mtx.js

0% Statements 0/177
0% Branches 0/84
0% Functions 0/13
0% Lines 0/174

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/*!
 * mtx.js - MTX extended for multisig
 * Copyright (c) 2018, The Bcoin Developers (MIT License).
 * https://github.com/bcoin-org/bmultisig
 */
 
'use strict';
 
const assert = require('bsert');
const {enforce} = assert;
const MTX = require('bcoin/lib/primitives/mtx');
const Coin = require('bcoin/lib/primitives/coin');
const Script = require('bcoin/lib/script/script');
const Witness = require('bcoin/lib/script/witness');
 
/**
 * Multisig MTX
 * TODO: throw correct errors.
 * @alias module:primitives.MultisigMTX
 */
 
class MultisigMTX extends MTX {
  constructor(options) {
    super(options);
  }
 
  /**
   * Check if coin we are spending
   * is witness.
   * TODO: Belongs to Coin.
   * @param {Coin} coin
   * @param {KeyRing} ring
   * @returns {Boolean} - true if it's witness program,
   * false if it is normal or ring does not own coin.
   */
 
  isWitnessCoin(coin, ring) {
    assert(ring.ownOutput(coin), 'Coin does not belong to the ring.');
    const prev = coin.script;
 
    if (prev.isProgram())
      return true;
 
    const sh = prev.getScripthash();
 
    if (sh) {
      const redeem = ring.getRedeem(sh);
 
      // should not happen
      if (!redeem)
        throw new Error('redeem script not found.');
 
      if (redeem.isProgram())
        return true;
    }
 
    return false;
  }
 
  /**
   * Get script to sign.
   * TODO: Belongs to Coin.
   * @param {Coin} coin
   * @param {KeyRing} ring
   * @returns {Script?}
   */
 
  getPrevScript(coin, ring) {
    const prev = coin.script;
 
    const sh = prev.getScripthash();
 
    if (sh) {
      const redeem = ring.getRedeem(sh);
 
      if (!redeem)
        return null;
 
      // Regular P2SH.
      if (!redeem.isProgram())
        return redeem.clone();
 
      // nested P2WSH
      const wsh = redeem.getWitnessScripthash();
 
      if (wsh) {
        const wredeem = ring.getRedeem(wsh);
 
        if (!wredeem)
          return null;
 
        return wredeem.clone();
      }
 
      // nested P2WPKH
      const wpkh = redeem.getWitnessPubkeyhash();
 
      if (wpkh)
        return Script.fromPubkeyhash(wpkh);
 
      // Unknown witness program.
      return null;
    }
 
    // normal output.
    if (!prev.isProgram())
      return prev.clone();
 
    // P2WSH
    const wsh = prev.getWitnessScripthash();
 
    if (wsh) {
      const wredeem = ring.getRedeem(wsh);
 
      if (!wredeem)
        return null;
 
      return wredeem.clone();
    }
 
    // P2WPKH
    const wpkh = prev.getWitnessPubkeyhash();
 
    if (wpkh)
      return Script.fromPubkeyhash(wpkh);
 
    return null;
  }
 
  /**
   * Verify signature without modifying transaction
   * TODO: move to TX
   * TODO: verifySignature
   * @param {Number} index - index of input being verified.
   * @param {Coin} coin
   * @param {KeyRing} ring
   * @param {Buffer} signature
   * @param {SighashType} type
   * @return {Boolean}
   */
 
  checkSignature(index, coin, ring, signature) {
    const input = this.inputs[index];
    const value = coin.value;
 
    assert(input, 'Input does not exist.');
    enforce(Coin.isCoin(coin), 'coin', 'Coin');
    enforce(Buffer.isBuffer(signature), 'signature', 'buffer');
 
    const prev = this.getPrevScript(coin, ring);
    const version = this.isWitnessCoin(coin, ring) ? 1 : 0;
    const key = ring.publicKey;
 
    return this.checksig(index, prev, value, signature, key, version);
  }
 
  /**
   * Sign and return signature
   * TODO: move to TX
   * TODO: Rename
   * @param {Number} index - index of input being signed.
   * @param {Coin|Output} coin
   * @param {KeyRing} ring
   * @param {SighashType} type
   * @returns {Buffer}
   */
 
  getInputSignature(index, coin, ring, type) {
    const input = this.inputs[index];
 
    assert(input, 'Input does not exist.');
    assert(coin, 'Input does not exist.');
    assert(ring.privateKey, 'No private key available.');
 
    const key = ring.privateKey;
    const value = coin.value;
    const version = this.isWitnessCoin(coin, ring) ? 1 : 0;
    const prev = this.getPrevScript(coin, ring);
 
    return this.signature(index, prev, value, key, type, version);
  }
 
  /**
   * Sign and return input signatures for a ring.
   * TODO: move to TX
   * TODO: rename
   * @param {KeyRing[]} rings - Keyring
   * @param {SighashType} type - Sighash type
   * @returns {Buffer[]}
   */
 
  getSignatures(rings, type) {
    assert(rings.length === this.inputs.length);
    const signatures = new Array(this.inputs.length);
 
    for (let i = 0; i < rings.length; i++) {
      const ring = rings[i];
 
      if (!ring)
        continue;
 
      const {prevout} = this.inputs[i];
      const coin = this.view.getOutput(prevout);
 
      if (!coin)
        continue;
 
      if (!ring.ownOutput(coin))
        throw new Error('Input does not belong to the key.');
 
      signatures[i] = this.getInputSignature(i, coin, ring, type);
    }
 
    return signatures;
  }
 
  /**
   * Apply signature without validating signature
   * @param {Number} index - index of input being signed.
   * @param {Coin|Output} coin
   * @param {KeyRing} ring
   * @param {Buffer} signature
   * @param {Boolean} valid - verify signature
   * @returns {Boolean} whether the signature was applied.
   */
 
  applySignature(index, coin, ring, signature, valid) {
    const input = this.inputs[index];
    const key = ring.publicKey;
 
    assert(input, 'Input does not exist.');
    assert(coin, 'No coin passed.');
    assert(signature, 'No signature passed.');
 
    // Get the previous output's script
    const value = coin.value;
    let prev = coin.script;
    let vector = input.script;
    let version = 0;
    let redeem = false;
 
    // Grab regular p2sh redeem script.
    if (prev.isScripthash()) {
      prev = input.script.getRedeem();
      if (!prev)
        throw new Error('Input has not been templated.');
      redeem = true;
    }
 
    // If the output script is a witness program,
    // we have to switch the vector to the witness
    // and potentially alter the length. Note that
    // witnesses are stack items, so the `dummy`
    // _has_ to be an empty buffer (what OP_0
    // pushes onto the stack).
    if (prev.isWitnessScripthash()) {
      prev = input.witness.getRedeem();
      if (!prev)
        throw new Error('Input has not been templated.');
      vector = input.witness;
      redeem = true;
      version = 1;
    } else {
      const wpkh = prev.getWitnessPubkeyhash();
      if (wpkh) {
        prev = Script.fromPubkeyhash(wpkh);
        vector = input.witness;
        redeem = false;
        version = 1;
      }
    }
 
    if (valid && !this.checksig(index, prev, value, signature, key, version))
      return false;
 
    if (redeem) {
      const stack = vector.toStack();
      const redeem = stack.pop();
 
      const result = this.signVector(prev, stack, signature, ring);
 
      if (!result)
        return false;
 
      result.push(redeem);
 
      vector.fromStack(result);
 
      return true;
    }
 
    const stack = vector.toStack();
    const result = this.signVector(prev, stack, signature, ring);
 
    if (!result)
      return false;
 
    vector.fromStack(result);
 
    return true;
  }
 
  /**
   * Apply signatures without validating signatures.
   * TODO: partially applied?
   * @param {KeyRing[]} rings - ring per signature
   * @param {Buffer[]} signatures - signatures
   * @param {Boolean} verify - should we verify applied signature(s)
   * @return {Boolean} whether the signature was applied.
   */
 
  applySignatures(rings, signatures, verify) {
    assert(signatures.length === this.inputs.length);
    assert(signatures.length === rings.length);
 
    for (let i = 0; i < signatures.length; i++) {
      const signature = signatures[i];
      const ring = rings[i];
 
      if (!signature)
        continue;
 
      if (!ring)
        throw new Error('Could not find key.');
 
      const {prevout} = this.inputs[i];
      const coin = this.view.getOutput(prevout);
 
      if (!coin)
        throw new Error('Could not find coin.');
 
      if (!ring.ownOutput(coin))
        throw new Error('Coin does not belong to the key.');
 
      // Build script for input
      if (!this.scriptInput(i, coin, ring))
        continue;
 
      if (!this.applySignature(i, coin, ring, signature, verify))
        return false;
    }
 
    return true;
  }
 
  /**
   * Check signatures
   * @param {KeyRing[]} rings - ring per signature
   * @param {Buffer[]} signatures
   * @returns {Number} number of valid signatures
   */
 
  checkSignatures(rings, signatures) {
    assert(signatures.length === this.inputs.length);
 
    let valid = 0;
 
    for (let i = 0; i < signatures.length; i++) {
      const signature = signatures[i];
      const ring = rings[i];
 
      if (!signature)
        continue;
 
      if (!ring)
        throw new Error('Could not find key.');
 
      const {prevout} = this.inputs[i];
      const coin = this.view.getCoin(prevout);
 
      if (!coin)
        throw new Error('Could not find coin.');
 
      if (!ring.ownOutput(coin))
        throw new Error('Coin does not belong to the key.');
 
      if (this.checkSignature(i, coin, ring, signature))
        valid += 1;
    }
 
    return valid;
  }
 
  /**
   * Empties input scripts and witness
   */
 
  emptyInputs() {
    for (const input of this.inputs) {
      const {script, witness} = input;
 
      if (script.length > 0)
        input.script = new Script();
 
      if (witness.length > 0)
        input.witness = new Witness();
    }
  }
 
  toMTX() {
    return new MTX().inject(this);
  }
 
  /**
   * Instantiate MultisigMTX from MTX.
   * @param {MTX} mtx
   * @returns {MultisigMTX}
   */
 
  static fromMTX(mtx) {
    return new this().inject(mtx);
  }
 
  /**
   * Test whether an object is a MultisigMTX.
   * @param {Object} obj
   * @returns {Boolean}
   */
 
  static isMultisigMTX(obj) {
    return obj instanceof MultisigMTX;
  }
}
 
/*
 * Expose
 */
 
module.exports = MultisigMTX;