class Factom::Client

Constants

ADDRESS_PREFIX
PREFIX_EC
PREFIX_FA

Attributes

endpoint[R]

Public Class Methods

new(endpoint, ec_private_key, version='v1') click to toggle source
# File lib/factom-ruby/client.rb, line 202
def initialize(endpoint, ec_private_key, version='v1')
  @endpoint = endpoint.gsub(/\/\z/, '')
  @ec_private_key = ec_private_key =~ /\A#{PREFIX_EC}/ ? address_to_pubkey(ec_private_key) : ec_private_key
  self.instance_eval { extend ::Factom.const_get("API#{version}", false) }
end

Public Instance Methods

address_to_pubkey(addr) click to toggle source

to pubkey in hex, 32 bytes

# File lib/factom-ruby/client.rb, line 236
def address_to_pubkey(addr)
  return unless addr.size == 52

  prefix = ADDRESS_PREFIX[addr[0,2]]
  return unless prefix

  v = Bitcoin.decode_base58(addr)
  return if v[0,4] != prefix

  bytes = [v[0, 68]].pack('H*')
  return if v[68, 8] != sha256d(bytes)[0, 8]

  v[4, 64]
end
ec_address() click to toggle source
# File lib/factom-ruby/client.rb, line 231
def ec_address
  @ec_address ||= pubkey_to_address ADDRESS_PREFIX[PREFIX_EC], ec_public_key
end
ec_public_key() click to toggle source
# File lib/factom-ruby/client.rb, line 227
def ec_public_key
  @ec_public_key ||= signing_key.verify_key.to_s.unpack('H*').first
end
get(path, params={}, options={}) click to toggle source
# File lib/factom-ruby/client.rb, line 216
def get(path, params={}, options={})
  JSON.parse raw_get(path, params, options)
end
pubkey_to_address(prefix, pubkey) click to toggle source
# File lib/factom-ruby/client.rb, line 251
def pubkey_to_address(prefix, pubkey)
  return unless pubkey.size == 64 # 32 bytes in hex

  addr = "#{prefix}#{pubkey}"
  bytes = [addr].pack('H*')

  Bitcoin.encode_base58 "#{addr}#{sha256d(bytes)[0,8]}"
end
raw_get(path, params={}, options={}) click to toggle source
# File lib/factom-ruby/client.rb, line 208
def raw_get(path, params={}, options={})
  uri = "#{endpoint}#{path}"
  options = {accept: :json}.merge(options)
  options[:params] = params

  RestClient.get uri, options
end
raw_post(path, params={}, options={}) click to toggle source
# File lib/factom-ruby/client.rb, line 220
def raw_post(path, params={}, options={})
  uri = "#{endpoint}#{path}"
  options = {accept: :json}.merge(options)

  RestClient.post uri, params, options
end
sha256d(bytes) click to toggle source
# File lib/factom-ruby/client.rb, line 260
def sha256d(bytes)
  Digest::SHA256.hexdigest(Digest::SHA256.digest(bytes))
end
sign(message) click to toggle source
# File lib/factom-ruby/client.rb, line 269
def sign(message)
  sig = signing_key.sign([message].pack('H*')).unpack('H*').first
  "#{message}#{ec_public_key}#{sig}"
end
signing_key() click to toggle source

ed25519 private key

# File lib/factom-ruby/client.rb, line 265
def signing_key
  @signing_key ||= RbNaCl::SigningKey.new([@ec_private_key].pack('H*'))
end