signature.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var BN = require('bn.js');
  3. var utils = require('../utils');
  4. var assert = utils.assert;
  5. var cachedProperty = utils.cachedProperty;
  6. var parseBytes = utils.parseBytes;
  7. /**
  8. * @param {EDDSA} eddsa - eddsa instance
  9. * @param {Array<Bytes>|Object} sig -
  10. * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
  11. * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
  12. * @param {Array<Bytes>} [sig.Rencoded] - R point encoded
  13. * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
  14. */
  15. function Signature(eddsa, sig) {
  16. this.eddsa = eddsa;
  17. if (typeof sig !== 'object')
  18. sig = parseBytes(sig);
  19. if (Array.isArray(sig)) {
  20. sig = {
  21. R: sig.slice(0, eddsa.encodingLength),
  22. S: sig.slice(eddsa.encodingLength)
  23. };
  24. }
  25. assert(sig.R && sig.S, 'Signature without R or S');
  26. if (eddsa.isPoint(sig.R))
  27. this._R = sig.R;
  28. if (sig.S instanceof BN)
  29. this._S = sig.S;
  30. this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
  31. this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
  32. }
  33. cachedProperty(Signature, 'S', function S() {
  34. return this.eddsa.decodeInt(this.Sencoded());
  35. });
  36. cachedProperty(Signature, 'R', function R() {
  37. return this.eddsa.decodePoint(this.Rencoded());
  38. });
  39. cachedProperty(Signature, 'Rencoded', function Rencoded() {
  40. return this.eddsa.encodePoint(this.R());
  41. });
  42. cachedProperty(Signature, 'Sencoded', function Sencoded() {
  43. return this.eddsa.encodeInt(this.S());
  44. });
  45. Signature.prototype.toBytes = function toBytes() {
  46. return this.Rencoded().concat(this.Sencoded());
  47. };
  48. Signature.prototype.toHex = function toHex() {
  49. return utils.encode(this.toBytes(), 'hex').toUpperCase();
  50. };
  51. module.exports = Signature;