class Rack::Lightning

Constants

VERSION

Public Class Methods

new(app, options={}) click to toggle source
# File lib/rack/lightning.rb, line 8
def initialize(app, options={})
  @app = app
  @invoice_storage = {} # TODO: don't store this in memory!
  @options = options
  @price = @options[:price] || 100
  @options[:address] ||= 'localhost:10009'
  @options[:timeout] ||= 5
  @options[:credentials] ||= ::File.read(::File.expand_path(@options[:credentials_path] || "~/.lnd/tls.cert"))
  @options[:macaroon] ||= begin
    macaroon_binary = ::File.read(::File.expand_path(@options[:macaroon_path] || "~/.lnd/data/chain/bitcoin/testnet/admin.macaroon"))
    macaroon_binary.each_byte.map { |b| b.to_s(16).rjust(2,'0') }.join
  end
  @lnd_client = Lnrpc::Lightning::Stub.new(@options[:address], GRPC::Core::ChannelCredentials.new(@options[:credentials]))
end

Public Instance Methods

call(env) click to toggle source
# File lib/rack/lightning.rb, line 23
def call(env)
  if self.paid?(env)
    @app.call(env)
  else
    invoice = self.generate_invoice(env)
    [402, { 'Content-Type' => 'application/vnd.lightning.bolt11' }, [invoice.payment_request]]
  end
end
generate_invoice(env) click to toggle source
# File lib/rack/lightning.rb, line 70
def generate_invoice(env)
  invoice_request = Lnrpc::Invoice.new(memo: "API request #{env['REQUEST_URI']}", value: self.price)
  @lnd_client.add_invoice(invoice_request, { metadata: { macaroon: @options[:macaroon] }})
end
hash_preimage(preimage) click to toggle source
# File lib/rack/lightning.rb, line 64
def hash_preimage(preimage)
  hexdecoded = preimage.pach('H*')
  hash = Digest::SHA256.digest(hexdecoded)
  hash.each_byte.map { |b| b.to_s(16).rjust(2, '0') }.join
end
paid?(env) click to toggle source
price() click to toggle source
# File lib/rack/lightning.rb, line 32
def price
  @price
end
used?(preimage_hash_hex) click to toggle source
# File lib/rack/lightning.rb, line 60
def used?(preimage_hash_hex)
  !@invoice_storage[preimage_hash_hex].nil?
end