polynomial.js 1.6 KB

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