Module: StraightServer::GatewayModule

Included in:
GatewayOnConfig, GatewayOnDB
Defined in:
lib/straight-server/gateway.rb

Overview

This module contains common features of Gateway, later to be included in one of the classes below.

Defined Under Namespace

Classes: CallbackUrlBadResponse, GatewayInactive, NoBlockchainAdapters, NoPubkey, NoTestPubkey, NoWebsocketsForNewGateway, OrderCountersDisabled, WebsocketExists, WebsocketForCompletedOrder

Constant Summary collapse

CALLBACK_URL_ATTEMPT_TIMEFRAME =

seconds

3600
@@websockets =
{}

Instance Method Summary collapse

Instance Method Details

#add_websocket_for_order(ws, order) ⇒ Object

Raises:



177
178
179
180
181
182
183
184
185
186
187
# File 'lib/straight-server/gateway.rb', line 177

def add_websocket_for_order(ws, order)
  raise WebsocketExists            unless websockets[order.id].nil?
  raise WebsocketForCompletedOrder unless order.status < 2
  StraightServer.logger.info "Opening ws connection for #{order.id}"
  ws.on(:close) do |event|
    websockets.delete(order.id)
    StraightServer.logger.info "Closing ws connection for #{order.id}"
  end
  websockets[order.id] = ws
  ws
end

#create_order(attrs = {}) ⇒ Object

Creates a new order and saves into the DB. Checks if the MD5 hash is correct first.

Raises:



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/straight-server/gateway.rb', line 123

def create_order(attrs={})

  raise GatewayInactive unless self.active

  StraightServer.logger.info "Creating new order with attrs: #{attrs}"

  # If we decide to reuse the order, we simply need to supply the
  # keychain_id that was used in the order we're reusing.
  # The address will be generated correctly.
  if reused_order = find_reusable_order
    attrs[:keychain_id] = reused_order.keychain_id

  end
  
  attrs[:keychain_id] = nil if attrs[:keychain_id] == ''


  order = new_order(
    amount:           (attrs[:amount] && attrs[:amount].to_f),
    keychain_id:      attrs[:keychain_id] || get_next_last_keychain_id,
    currency:         attrs[:currency],
    btc_denomination: attrs[:btc_denomination]
  )

  order.id            = attrs[:id].to_i       if attrs[:id]
  order.data          = attrs[:data]          if attrs[:data]
  order.callback_data = attrs[:callback_data] if attrs[:callback_data]
  order.title         = attrs[:title]         if attrs[:title]
  order.callback_url  = attrs[:callback_url]  if attrs[:callback_url]
  order.gateway       = self
  order.test_mode     = test_mode
  order.description   = attrs[:description]
  order.reused        = reused_order.reused + 1 if reused_order
  order.save

  self.update_last_keychain_id(attrs[:keychain_id]) unless order.reused > 0
  self.save
  StraightServer.logger.info "Order #{order.id} created: #{order.to_h}"
  order
end

#fetch_transactions_for(address) ⇒ Object

END OF Initializers methods ##################################################



114
115
116
117
118
119
# File 'lib/straight-server/gateway.rb', line 114

def fetch_transactions_for(address)
  super
rescue Straight::Blockchain::Adapter::BitcoinAddressInvalid => e
  StraightServer.logger.warn "Address seems to be invalid, ignoring it. #{e.message}"
  return []
end

#find_reusable_orderObject

If we have more than Config.reuse_address_orders_threshold i a row for this gateway, this method returns the one which keychain_id (and, consequently, address) is to be reused. It also checks (just in case) if any transactions has been made to the addres-to-be-reused, because even though the order itself might be expired, the address might have been used for something else.

If there were transactions to it, there’s actually no need to reuse the address and we can safely return nil.

Also, see comments for #find_expired_orders_row method.



251
252
253
254
255
256
257
258
# File 'lib/straight-server/gateway.rb', line 251

def find_reusable_order
  expired_orders = find_expired_orders_row
  if expired_orders.size >= Config.reuse_address_orders_threshold &&
  fetch_transactions_for(expired_orders.last.address).empty?
    return expired_orders.last
  end
  nil
end

#get_next_last_keychain_idObject



164
165
166
# File 'lib/straight-server/gateway.rb', line 164

def get_next_last_keychain_id
  self.test_mode ? self.test_last_keychain_id + 1 : self.last_keychain_id + 1
end

#get_order_counter(counter_name) ⇒ Object



231
232
233
234
# File 'lib/straight-server/gateway.rb', line 231

def get_order_counter(counter_name)
  raise OrderCountersDisabled unless StraightServer::Config.count_orders
  StraightServer.redis_connection.get("#{StraightServer::Config.redis[:prefix]}:gateway_#{id}:#{counter_name}_orders_counter").to_i || 0
end

#increment_order_counter!(counter_name, by = 1) ⇒ Object



236
237
238
239
# File 'lib/straight-server/gateway.rb', line 236

def increment_order_counter!(counter_name, by=1)
  raise OrderCountersDisabled unless StraightServer::Config.count_orders
  StraightServer.redis_connection.incrby("#{StraightServer::Config.redis[:prefix]}:gateway_#{id}:#{counter_name}_orders_counter", by)
end

#initialize_blockchain_adaptersObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/straight-server/gateway.rb', line 72

def initialize_blockchain_adapters
  @blockchain_adapters = []
  StraightServer::Config.blockchain_adapters.each do |a|

    adapter = Straight::Blockchain.const_get("#{a}Adapter")
    next unless adapter
    begin
      main_url = StraightServer::Config.__send__("#{a.downcase}_url") rescue next
      test_url = StraightServer::Config.__send__("#{a.downcase}_test_url") rescue nil
      @blockchain_adapters << adapter.mainnet_adapter(main_url: main_url, test_url: test_url)
    rescue ArgumentError
      @blockchain_adapters << adapter.mainnet_adapter
    end
  end
  raise NoBlockchainAdapters if @blockchain_adapters.empty?
end

#initialize_callbacksObject



89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/straight-server/gateway.rb', line 89

def initialize_callbacks
  # When the status of an order changes, we send an http request to the callback_url
  # and also notify a websocket client (if present, of course).
  @order_callbacks = [
    lambda do |order|
      StraightServer::Thread.new do
        send_order_to_websocket_client order
      end
      StraightServer::Thread.new do
        send_callback_http_request order
      end
    end
  ]
end

#initialize_exchange_rate_adaptersObject

Initializers methods ######################################################## We have separate methods, because with GatewayOnDB they are called from #after_initialize but in GatewayOnConfig they are called from #initialize intself. #########################################################################################



59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/straight-server/gateway.rb', line 59

def initialize_exchange_rate_adapters
  @exchange_rate_adapters ||= []
  if self.exchange_rate_adapter_names.kind_of?(Array) && self.exchange_rate_adapter_names
    self.exchange_rate_adapter_names.each do |adapter|
      begin
        @exchange_rate_adapters << Straight::ExchangeRate.const_get("#{adapter}Adapter").instance
      rescue NameError => e
        puts "WARNING: No exchange rate adapter with the name #{adapter} was found!"
      end
    end
  end
end

#initialize_networkObject



108
109
110
# File 'lib/straight-server/gateway.rb', line 108

def initialize_network
  BTC::Network.default = test_mode ? BTC::Network.testnet : BTC::Network.mainnet
end

#initialize_status_check_scheduleObject



104
105
106
# File 'lib/straight-server/gateway.rb', line 104

def initialize_status_check_schedule
  @status_check_schedule = Straight::GatewayModule::DEFAULT_STATUS_CHECK_SCHEDULE
end

#order_counters(reload: false) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/straight-server/gateway.rb', line 218

def order_counters(reload: false)
  return @order_counters if @order_counters && !reload
  @order_counters = {
    new:         get_order_counter(:new),
    unconfirmed: get_order_counter(:unconfirmed),
    paid:        get_order_counter(:paid),
    underpaid:   get_order_counter(:underpaid),
    overpaid:    get_order_counter(:overpaid),
    expired:     get_order_counter(:expired),
    canceled:    get_order_counter(:canceled),
  }
end

#order_status_changed(order) ⇒ Object



209
210
211
212
213
214
215
216
# File 'lib/straight-server/gateway.rb', line 209

def order_status_changed(order)
  statuses = Order::STATUSES.invert
  if StraightServer::Config.count_orders
    increment_order_counter!(statuses[order.old_status], -1) if order.old_status
    increment_order_counter!(statuses[order.status])
  end
  super
end

#send_order_to_websocket_client(order) ⇒ Object



194
195
196
197
198
199
# File 'lib/straight-server/gateway.rb', line 194

def send_order_to_websocket_client(order)
  if ws = websockets[order.id]
    ws.send(order.to_json)
    ws.close
  end
end

#sign_with_secret(content, level: 1) ⇒ Object



201
202
203
204
205
206
207
# File 'lib/straight-server/gateway.rb', line 201

def sign_with_secret(content, level: 1)
  result = content.to_s
  level.times do
    result = OpenSSL::HMAC.digest('sha256', secret, result).unpack("H*").first
  end
  result
end

#update_last_keychain_id(new_value = nil) ⇒ Object

TODO: make it pretty



169
170
171
172
173
174
175
# File 'lib/straight-server/gateway.rb', line 169

def update_last_keychain_id(new_value=nil)
  if self.test_mode
    new_value ? self.test_last_keychain_id = new_value : self.test_last_keychain_id += 1
  else
    new_value ? self.last_keychain_id = new_value : self.last_keychain_id += 1
  end
end

#websocketsObject



189
190
191
192
# File 'lib/straight-server/gateway.rb', line 189

def websockets
  raise NoWebsocketsForNewGateway unless self.id
  @@websockets[self.id]
end