d232ecb63efec878e8d4efc002feeb6dfe541698aeae599ab2f7dcdf3242de10ba1863e7da088f2ac655d139d91955df5786be2739884d2804183f7f24b109 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. assert(sig.length === eddsa.encodingLength * 2, 'Signature has invalid size');
  21. sig = {
  22. R: sig.slice(0, eddsa.encodingLength),
  23. S: sig.slice(eddsa.encodingLength),
  24. };
  25. }
  26. assert(sig.R && sig.S, 'Signature without R or S');
  27. if (eddsa.isPoint(sig.R))
  28. this._R = sig.R;
  29. if (sig.S instanceof BN)
  30. this._S = sig.S;
  31. this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
  32. this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
  33. }
  34. cachedProperty(Signature, 'S', function S() {
  35. return this.eddsa.decodeInt(this.Sencoded());
  36. });
  37. cachedProperty(Signature, 'R', function R() {
  38. return this.eddsa.decodePoint(this.Rencoded());
  39. });
  40. cachedProperty(Signature, 'Rencoded', function Rencoded() {
  41. return this.eddsa.encodePoint(this.R());
  42. });
  43. cachedProperty(Signature, 'Sencoded', function Sencoded() {
  44. return this.eddsa.encodeInt(this.S());
  45. });
  46. Signature.prototype.toBytes = function toBytes() {
  47. return this.Rencoded().concat(this.Sencoded());
  48. };
  49. Signature.prototype.toHex = function toHex() {
  50. return utils.encode(this.toBytes(), 'hex').toUpperCase();
  51. };
  52. module.exports = Signature;