Module: Ciri::Utils

Extended by:
Number
Defined in:
lib/ciri/utils.rb,
lib/ciri/utils/logger.rb,
lib/ciri/utils/number.rb,
lib/ciri/utils/version.rb

Defined Under Namespace

Modules: Logger, Number

Constant Summary collapse

BLANK_SHA3 =
Utils.keccak(''.b).freeze
VERSION =
"0.2.2"

Constants included from Number

Number::UINT_255_CEILING, Number::UINT_255_MAX, Number::UINT_256_CEILING, Number::UINT_256_MAX

Class Method Summary collapse

Methods included from Number

big_endian_decode, big_endian_encode, ceil_div, signed_to_unsigned, unsigned_to_signed

Class Method Details

.blank?(item) ⇒ Boolean



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/ciri/utils.rb', line 63

def blank?(item)
  if item.nil?
    true
  elsif item.is_a? Integer
    item.zero?
  elsif item.is_a? String
    item.empty?
  else
    false
  end
end

.blank_bytes?(item) ⇒ Boolean



58
59
60
61
# File 'lib/ciri/utils.rb', line 58

def blank_bytes?(item)
  return true if item.is_a?(String) && item.each_byte.all?(&:zero?)
  blank?(item)
end

.create_ec_pk(raw_pubkey: nil, raw_privkey: nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ciri/utils.rb', line 41

def create_ec_pk(raw_pubkey: nil, raw_privkey: nil)
  public_key = raw_pubkey && begin
    group = OpenSSL::PKey::EC::Group.new('secp256k1')
    bn = OpenSSL::BN.new(raw_pubkey, 2)
    OpenSSL::PKey::EC::Point.new(group, bn)
  end

  OpenSSL::PKey::EC.new('secp256k1').tap do |key|
    key.public_key = public_key if public_key
    key.private_key = OpenSSL::BN.new(raw_privkey, 2) if raw_privkey
  end
end

.hex_to_number(hex) ⇒ Object



28
29
30
# File 'lib/ciri/utils.rb', line 28

def hex_to_number(hex)
  big_endian_decode to_bytes(hex)
end

.keccak(*data, bits: 256) ⇒ Object



13
14
15
16
17
# File 'lib/ciri/utils.rb', line 13

def keccak(*data, bits: 256)
  s = Digest::SHA3.new(bits)
  data.each {|i| s.update(i)}
  s.digest
end

.number_to_hex(number) ⇒ Object



37
38
39
# File 'lib/ciri/utils.rb', line 37

def number_to_hex(number)
  to_hex big_endian_encode(number)
end

.present?(item) ⇒ Boolean



75
76
77
# File 'lib/ciri/utils.rb', line 75

def present?(item)
  !blank?(item)
end

.secret_compare(s1, s2) ⇒ Object



19
20
21
# File 'lib/ciri/utils.rb', line 19

def secret_compare(s1, s2)
  s1.size == s2.size && s1.each_byte.each_with_index.map {|b, i| b ^ s2[i].ord}.reduce(0, :+) == 0
end

.to_bytes(hex) ⇒ Object



23
24
25
26
# File 'lib/ciri/utils.rb', line 23

def to_bytes(hex)
  hex = hex[2..-1] if hex.start_with?('0x')
  [hex].pack("H*")
end

.to_hex(data) ⇒ Object



32
33
34
35
# File 'lib/ciri/utils.rb', line 32

def to_hex(data)
  hex = data.to_s.unpack("H*").first
  '0x' + hex
end

.to_underscore(str) ⇒ Object



54
55
56
# File 'lib/ciri/utils.rb', line 54

def to_underscore(str)
  str.gsub(/[A-Z]/) {|a| "_" + a.downcase}
end