polynomial.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. const GF = require('./galois-field')
  2. /**
  3. * Multiplies two polynomials inside Galois Field
  4. *
  5. * @param {Uint8Array} p1 Polynomial
  6. * @param {Uint8Array} p2 Polynomial
  7. * @return {Uint8Array} Product of p1 and p2
  8. */
  9. exports.mul = function mul (p1, p2) {
  10. const coeff = new Uint8Array(p1.length + p2.length - 1)
  11. for (let i = 0; i < p1.length; i++) {
  12. for (let j = 0; j < p2.length; j++) {
  13. coeff[i + j] ^= GF.mul(p1[i], p2[j])
  14. }
  15. }
  16. return coeff
  17. }
  18. /**
  19. * Calculate the remainder of polynomials division
  20. *
  21. * @param {Uint8Array} divident Polynomial
  22. * @param {Uint8Array} divisor Polynomial
  23. * @return {Uint8Array} Remainder
  24. */
  25. exports.mod = function mod (divident, divisor) {
  26. let result = new Uint8Array(divident)
  27. while ((result.length - divisor.length) >= 0) {
  28. const coeff = result[0]
  29. for (let i = 0; i < divisor.length; i++) {
  30. result[i] ^= GF.mul(divisor[i], coeff)
  31. }
  32. // remove all zeros from buffer head
  33. let offset = 0
  34. while (offset < result.length && result[offset] === 0) offset++
  35. result = result.slice(offset)
  36. }
  37. return result
  38. }
  39. /**
  40. * Generate an irreducible generator polynomial of specified degree
  41. * (used by Reed-Solomon encoder)
  42. *
  43. * @param {Number} degree Degree of the generator polynomial
  44. * @return {Uint8Array} Buffer containing polynomial coefficients
  45. */
  46. exports.generateECPolynomial = function generateECPolynomial (degree) {
  47. let poly = new Uint8Array([1])
  48. for (let i = 0; i < degree; i++) {
  49. poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]))
  50. }
  51. return poly
  52. }