poseidon.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  2. // Poseidon Hash: https://eprint.iacr.org/2019/458.pdf, https://www.poseidon-hash.info
  3. import { FpPow, validateField } from './modular.js';
  4. export function validateOpts(opts) {
  5. const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts;
  6. const { roundsFull, roundsPartial, sboxPower, t } = opts;
  7. validateField(Fp);
  8. for (const i of ['t', 'roundsFull', 'roundsPartial']) {
  9. if (typeof opts[i] !== 'number' || !Number.isSafeInteger(opts[i]))
  10. throw new Error(`Poseidon: invalid param ${i}=${opts[i]} (${typeof opts[i]})`);
  11. }
  12. // MDS is TxT matrix
  13. if (!Array.isArray(mds) || mds.length !== t)
  14. throw new Error('Poseidon: wrong MDS matrix');
  15. const _mds = mds.map((mdsRow) => {
  16. if (!Array.isArray(mdsRow) || mdsRow.length !== t)
  17. throw new Error(`Poseidon MDS matrix row: ${mdsRow}`);
  18. return mdsRow.map((i) => {
  19. if (typeof i !== 'bigint')
  20. throw new Error(`Poseidon MDS matrix value=${i}`);
  21. return Fp.create(i);
  22. });
  23. });
  24. if (rev !== undefined && typeof rev !== 'boolean')
  25. throw new Error(`Poseidon: invalid param reversePartialPowIdx=${rev}`);
  26. if (roundsFull % 2 !== 0)
  27. throw new Error(`Poseidon roundsFull is not even: ${roundsFull}`);
  28. const rounds = roundsFull + roundsPartial;
  29. if (!Array.isArray(rc) || rc.length !== rounds)
  30. throw new Error('Poseidon: wrong round constants');
  31. const roundConstants = rc.map((rc) => {
  32. if (!Array.isArray(rc) || rc.length !== t)
  33. throw new Error(`Poseidon wrong round constants: ${rc}`);
  34. return rc.map((i) => {
  35. if (typeof i !== 'bigint' || !Fp.isValid(i))
  36. throw new Error(`Poseidon wrong round constant=${i}`);
  37. return Fp.create(i);
  38. });
  39. });
  40. if (!sboxPower || ![3, 5, 7].includes(sboxPower))
  41. throw new Error(`Poseidon wrong sboxPower=${sboxPower}`);
  42. const _sboxPower = BigInt(sboxPower);
  43. let sboxFn = (n) => FpPow(Fp, n, _sboxPower);
  44. // Unwrapped sbox power for common cases (195->142μs)
  45. if (sboxPower === 3)
  46. sboxFn = (n) => Fp.mul(Fp.sqrN(n), n);
  47. else if (sboxPower === 5)
  48. sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n);
  49. return Object.freeze({ ...opts, rounds, sboxFn, roundConstants, mds: _mds });
  50. }
  51. export function splitConstants(rc, t) {
  52. if (typeof t !== 'number')
  53. throw new Error('poseidonSplitConstants: wrong t');
  54. if (!Array.isArray(rc) || rc.length % t)
  55. throw new Error('poseidonSplitConstants: wrong rc');
  56. const res = [];
  57. let tmp = [];
  58. for (let i = 0; i < rc.length; i++) {
  59. tmp.push(rc[i]);
  60. if (tmp.length === t) {
  61. res.push(tmp);
  62. tmp = [];
  63. }
  64. }
  65. return res;
  66. }
  67. export function poseidon(opts) {
  68. const _opts = validateOpts(opts);
  69. const { Fp, mds, roundConstants, rounds, roundsPartial, sboxFn, t } = _opts;
  70. const halfRoundsFull = _opts.roundsFull / 2;
  71. const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0;
  72. const poseidonRound = (values, isFull, idx) => {
  73. values = values.map((i, j) => Fp.add(i, roundConstants[idx][j]));
  74. if (isFull)
  75. values = values.map((i) => sboxFn(i));
  76. else
  77. values[partialIdx] = sboxFn(values[partialIdx]);
  78. // Matrix multiplication
  79. values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO));
  80. return values;
  81. };
  82. const poseidonHash = function poseidonHash(values) {
  83. if (!Array.isArray(values) || values.length !== t)
  84. throw new Error(`Poseidon: wrong values (expected array of bigints with length ${t})`);
  85. values = values.map((i) => {
  86. if (typeof i !== 'bigint')
  87. throw new Error(`Poseidon: wrong value=${i} (${typeof i})`);
  88. return Fp.create(i);
  89. });
  90. let round = 0;
  91. // Apply r_f/2 full rounds.
  92. for (let i = 0; i < halfRoundsFull; i++)
  93. values = poseidonRound(values, true, round++);
  94. // Apply r_p partial rounds.
  95. for (let i = 0; i < roundsPartial; i++)
  96. values = poseidonRound(values, false, round++);
  97. // Apply r_f/2 full rounds.
  98. for (let i = 0; i < halfRoundsFull; i++)
  99. values = poseidonRound(values, true, round++);
  100. if (round !== rounds)
  101. throw new Error(`Poseidon: wrong number of rounds: last round=${round}, total=${rounds}`);
  102. return values;
  103. };
  104. // For verification in tests
  105. poseidonHash.roundConstants = roundConstants;
  106. return poseidonHash;
  107. }
  108. //# sourceMappingURL=poseidon.js.map