Module: BitcoinCigs::MathHelper

Included in:
BitcoinCigs, Point
Defined in:
lib/bitcoin_cigs/math_helper.rb

Instance Method Summary collapse

Instance Method Details

#inverse_mod(a, m) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/bitcoin_cigs/math_helper.rb', line 6

def inverse_mod(a, m)
  a = a % m if a < 0 || m <= a
  
  c, d = a, m
  
  uc, vc, ud, vd = 1, 0, 0, 1
  
  while c != 0
    q, c, d = d / c, d % c, c
    uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
  end
  raise ::BitcoinCigs::Error.new unless d == 1
  
  ud > 0 ? ud : ud + m
end

#leftmost_bit(x) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/bitcoin_cigs/math_helper.rb', line 22

def leftmost_bit(x)
  raise ::BitcoinCigs::Error.new unless x > 0
  
  result = 1
  result *= 2 while result <= x
  result / 2
end

#ripemd160(d) ⇒ Object



30
31
32
# File 'lib/bitcoin_cigs/math_helper.rb', line 30

def ripemd160(d)
  (OpenSSL::Digest::RIPEMD160.new << d).digest
end

#sha256(d) ⇒ Object



34
35
36
# File 'lib/bitcoin_cigs/math_helper.rb', line 34

def sha256(d)
  (Digest::SHA2.new << d).digest
end

#sqrt_mod(a, p) ⇒ Object



38
39
40
# File 'lib/bitcoin_cigs/math_helper.rb', line 38

def sqrt_mod(a, p)
  a.to_bn.mod_exp((p + 1) / 4, p).to_i
end

#str_to_num(s) ⇒ Object



42
43
44
# File 'lib/bitcoin_cigs/math_helper.rb', line 42

def str_to_num(s)
  s.chars.reverse_each.with_index.inject(0) { |acc, (ch, i)| acc + ch.ord * (256 ** i) }
end