Skip to content

Instantly share code, notes, and snippets.

@matiu
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matiu/a7e4531fa567d8e65a29 to your computer and use it in GitHub Desktop.
Save matiu/a7e4531fa567d8e65a29 to your computer and use it in GitHub Desktop.

Client / Sign and extract DER

var clientSign = function(tx, xpriv, n) {
  //Derive proper key to sign, for each input
  var privs = [],
    derived = {};
  var xpriv = new Bitcore.HDPrivateKey(someXPrivKey[0]);

  _.each(tx.inputs, function(i) {
    if (!derived[i.path]) {
      derived[i.path] = xpriv.derive(i.path).privateKey;
    } 
    privs.push(derived[i.path]);
  });

  var t = new Bitcore.Transaction();
  _.each(tx.inputs, function(i) {
    t.from(i, i.publicKeys, n);
  });

  t.to(tx.toAddress, tx.amount)
    .change(tx.changeAddress)
    .sign(privs);

  var signatures = [];
  _.each(privs, function(p) {
     var s = t.getSignatures(p)[0].signature.toDER().toString('hex');
     signatures.push(s);
   });
  //
  return signatures;
}

Server / Check signatures

TxProposal.prototype._getBitcoreTx = function(n) {
  var self = this;

  var t = new Bitcore.Transaction();
  _.each(this.inputs, function(i) {
    t.from(i, i.publicKeys, self.requiredSignatures)
  });

  t.to(this.toAddress, this.amount)
    .change(this.changeAddress);

  t._updateChangeOutput();

  return t;
};

TxProposal.prototype.checkSignatures = function(signatures, publicKey) {
  var self = this;
  var t = this._getBitcoreTx();

  if (signatures.length != this.inputs.length)
    return false;

  var oks = 0;
  var i = 0;
  _.each(signatures, function(signatureHex) {
    var input = self.inputs[i];
    var signature = Bitcore.crypto.Signature.fromString(signatureHex);

    var s = {
      inputIndex: i++,
      signature: signature,
      sigtype: Bitcore.crypto.Signature.SIGHASH_ALL,
      publicKey: new Bitcore.PublicKey(publicKey),
    };

    try {
      t.applySignature(s);
      oks++;
    } catch (e) {};
  });

  return oks === t.inputs.length;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment