repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
michaelgpearce/coinmux
bin/coinmux_gui.rb
<filename>bin/coinmux_gui.rb raise "COINMUX_ENV not set" if ENV['COINMUX_ENV'].nil? $: << File.join(File.dirname(__FILE__), '..') require 'lib/coinmux' if Coinmux.os == :macosx # Need to set app name before loading any AWT/Swing components { "com.apple.mrj.application.apple.menu.about.name" => "Coinmux", "apple.laf.useScreenMenuBar" => "true", }.each do |key, value| Java::JavaLang::System.setProperty(key, value) end icon = Java::JavaxSwing::ImageIcon.new(Coinmux::FileUtil.read_content_as_java_bytes("gui", "assets", "icon_320.png")) Java::ComAppleEawt::Application.getApplication().setDockIconImage(icon.getImage()) end module Gui module View; end module Component; end end require 'gui/event_queue' require 'gui/view/base' require 'gui/view/available_mixes' require 'gui/view/mix_settings' require 'gui/view/mixing' require 'gui/view/preferences' require 'gui/component/link_button' require 'gui/application' Gui::Application.new.start import 'javax.swing.SwingUtilities' if !Java::JavaxSwing::SwingUtilities.isEventDispatchThread() thread = nil Java::JavaxSwing::SwingUtilities.invokeAndWait do thread = Thread.current end thread.join end
michaelgpearce/coinmux
lib/coinmux/message/status.rb
<filename>lib/coinmux/message/status.rb class Coinmux::Message::Status < Coinmux::Message::Base property :state property :transaction_id validates :state, :presence => true validate :transaction_id_presence validate :state_valid class << self def build(coin_join, options = {}) options.assert_keys!(required: :state, optional: :transaction_id) message = super(coin_join.data_store, coin_join) message.state = options[:state] message.transaction_id = options[:transaction_id] message end end private def transaction_id_presence if state == 'completed' errors[:transaction_id] << "must be present for state #{state}" if transaction_id.nil? else errors[:transaction_id] << "must not be present for state #{state}" unless transaction_id.nil? end end def is_completed? state == 'completed' end def state_valid errors[:state] << "is not a valid state" unless Coinmux::StateMachine::Director::STATES.include?(state) end end
michaelgpearce/coinmux
spec/bitcoin_crypto_spec.rb
<gh_stars>10-100 require 'spec_helper' describe Coinmux::BitcoinCrypto do let(:message) { "this is a message" } let(:address) { "mh9nRF1ZSqLJB3hbUjPLmfDHdnGUURdYdK" } let(:private_key_hex) { "585C660C887913E5F40B8E34D99C62766443F9D043B1DE1DFDCC94E386BC6DF6" } let(:private_key_wif) { "<KEY>" } let(:private_key_wif_compressed) { "<KEY>" } let(:public_key_hex) { "<KEY>" } let(:signature_base_64) { "HIZQbBLAGJLhSZ310FCQMAo9l1X2ysxyt0kXkf6KcBN3znl2iClC6V9wz9Nkn6mMDUaq4kRlgYQDUUlsm29Bl0o=" } describe "#verify_message!" do subject { bitcoin_crypto_facade.verify_message!(message, signature_base_64, address) } it "returns true" do expect(subject).to be_true end end describe "#sign_message!" do subject { bitcoin_crypto_facade.sign_message!(message, private_key_hex) } it "verifies" do expect(bitcoin_crypto_facade.verify_message!(message, subject, address)).to be_true end end describe "#address_for_public_key!" do subject { bitcoin_crypto_facade.address_for_public_key!(public_key_hex) } it "returns the bitcoin address" do expect(subject).to eq(address) end end describe "#public_key_for_private_key!" do subject { bitcoin_crypto_facade.public_key_for_private_key!(private_key_hex) } it "returns the public key" do expect(subject).to eq(public_key_hex) end end describe "#address_for_private_key!" do subject { bitcoin_crypto_facade.address_for_private_key!(private_key_hex) } it "returns the address" do expect(subject).to eq(address) end end describe "#verify_address!" do subject { bitcoin_crypto_facade.verify_address!(address) } it "returns true" do expect(subject).to be_true end end describe "private_key_to_hex!" do subject { bitcoin_crypto_facade.private_key_to_hex!(private_key) } context "with private_key_hex" do let(:private_key) { private_key_hex } it "returns private key hex" do expect(subject).to eq(private_key_hex) end end context "with private_key_wif" do let(:private_key) { private_key_wif } it "returns private key hex" do expect(subject).to eq(private_key_hex) end end context "with private_key_wif_compressed" do let(:private_key) { private_key_wif_compressed } it "returns private key hex" do expect(subject).to eq(private_key_hex) end end context "with invalid key" do let(:private_key) { private_key_hex[0..10] } it "returns private key hex" do expect { subject }.to raise_exception(Coinmux::Error, "Private Key not valid") end end end end
michaelgpearce/coinmux
gui/view/available_mixes.rb
<gh_stars>10-100 class Gui::View::AvailableMixes < Gui::View::Base import 'java.awt.Dimension' import 'java.awt.GridLayout' import 'javax.swing.BorderFactory' import 'javax.swing.ListSelectionModel' import 'javax.swing.JButton' import 'javax.swing.JTextArea' import 'javax.swing.JScrollPane' import 'javax.swing.JTable' import 'javax.swing.event.TableModelEvent' import 'javax.swing.border.TitledBorder' import 'javax.swing.table.AbstractTableModel' import 'javax.swing.table.TableModel' def update_mixes_table(mixes_data) mixes_table.setMixesData(mixes_data) end protected def handle_add add_header("Mix Your Bitcoins", show_settings: true) add_row do |parent| label = JTextArea.new(<<-STRING) Coinmux is the safe way to mix your bitcoins. Your bitcoins are mixed with other Coinmux users on the Internet, but your private Bitcoin information never leaves your computer. You are always 100% in control of your bitcoins and you never need to trust a 3rd party. STRING label.setEditable(false) label.setLineWrap(true) label.setWrapStyleWord(true) label.setBackground(parent.getBackground()) parent.add(label, build_grid_bag_constraints(gridy: 0, fill: :horizontal, anchor: :north)) end add_row do |parent| JPanel.new(GridLayout.new(1, 1)).tap do |panel| scroll_pane = JScrollPane.new(mixes_table) panel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEmptyBorder(), "Available Bitcoin Mixes", TitledBorder::LEFT, TitledBorder::TOP)) panel.add(scroll_pane) parent.add(panel, build_grid_bag_constraints(gridy: 1, fill: :both, anchor: :center, weighty: 1000000)) end end add_button_row(join_button, create_button) end def handle_show update_join_button_enabled update_create_button_enabled end private class MixesTable < JTable include Coinmux::BitcoinUtil def initialize super(TModel.new) getModel().setData([["Loading...", ""]]) end def setMixesData(mixes_data) data = if mixes_data.blank? [["Nothing available", ""]] else mixes_data.collect do |mix_data| [mix_data[:amount].to_f / SATOSHIS_PER_BITCOIN, "#{mix_data[:waiting_participants]} of #{mix_data[:total_participants]}"] end end getModel().setData(data) end def hasMixes() # we sometimes put some text in [0][0], not the bitcoin amount getModel().getData()[0][0].to_f != 0 end def tableChanged(event) return super(event) unless hasMixes() && (selected_index = getSelectedIndex()) >= 0 previous_amount = getAmountFromData(selected_index, event.getPreviousData()) previous_participants = getParticipantsFromData(selected_index, event.getPreviousData()) super(event) selectAmountAndParticipants(previous_amount, previous_participants) end def getSelectedIndex() getSelectionModel().getMinSelectionIndex() end def getAmount(row_index) getAmountFromData(row_index) end def getParticipants(row_index) getParticipantsFromData(row_index) end private def getAmountFromData(row_index, data = getModel().getData()) (data[row_index][0].to_f * SATOSHIS_PER_BITCOIN).to_i end def getParticipantsFromData(row_index, data = getModel().getData()) data[row_index][1].gsub(/.* /, '').to_i end def selectAmountAndParticipants(amount, participants) getModel().getRowCount().times do |row_index| if amount == getAmount(row_index) && participants == getParticipants(row_index) setRowSelectionInterval(row_index, row_index) break end end end end class TModelEvent < TableModelEvent def initialize(source, previous_data, current_data) super(source) @previous_data = previous_data @current_data = current_data end def getPreviousData(); @previous_data; end def getCurrentData(); @current_data; end end class TModel < AbstractTableModel def getData() data end def setData(data) self.data = data end def getColumnCount(); 2; end def getRowCount(); data.size; end def getColumnName(index) ["Bitcoin Amount (BTC)", "Participants"][index] end def getValueAt(row, col) data[row].try(:[], col) end def setValueAt(value, row, col) if value.nil? && row >= data.size self.data = data[0...row] else data[row] ||= [] data[row][col] = value end end private def data @data ||= [] end def data=(data) previous_data = @data @data = data if previous_data != data fireTableChanged(TModelEvent.new(self, previous_data, data)) end end end def join_button @join_button ||= JButton.new("Join Available Mix").tap do |join_button| join_button.add_action_listener do |e| application.show_view(:mix_settings) end end end def create_button @create_button ||= JButton.new("Create New Mix").tap do |create_button| create_button.add_action_listener do |e| application.amount = nil application.participants = nil application.show_view(:mix_settings) end end end def join_button @join_button ||= JButton.new("Join Available Mix").tap do |join_button| join_button.setEnabled(false) join_button.add_action_listener do |e| selected_index = mixes_table.getSelectedIndex() application.amount = mixes_table.getAmount(selected_index) application.participants = mixes_table.getParticipants(selected_index) application.show_view(:mix_settings) end end end def mixes_table @mixes_table ||= MixesTable.new.tap do |mixes_table| mixes_table.setSelectionMode(ListSelectionModel::SINGLE_SELECTION) mixes_table.getSelectionModel().addListSelectionListener do |e| update_join_button_enabled end mixes_table.getModel().addTableModelListener do |e| update_join_button_enabled end end end def update_create_button_enabled create_button.setEnabled(application.data_store.connected) end def update_join_button_enabled has_selected_mix = !mixes_table.getSelectionModel().isSelectionEmpty() && mixes_table.hasMixes() join_button.setEnabled(application.data_store.connected && has_selected_mix) end end
michaelgpearce/coinmux
lib/coinmux/digest.rb
require 'securerandom' require 'digest/sha2' class Coinmux::Digest include Singleton def digest(message) Digest::SHA2.new(256).digest(message) end def hex_message_digest(*params) message = params.join(':') hex_digest(message) end def hex_digest(message) digest(message).unpack('H*').first end def random_identifier SecureRandom.urlsafe_base64 end end
michaelgpearce/coinmux
lib/coinmux/config.rb
require 'yaml' require 'erb' class Coinmux::Config include Coinmux::Proper CONFIG = YAML.load(ERB.new(Coinmux::FileUtil.read_content('config', 'coinmux.yml')).result) property :name, :bitcoin_network, :coin_join_uris, :webbtc_host, :show_transaction_url class << self def configs @configs ||= %w(mainnet testnet test).each_with_object({}) do |config_key, configs| configs[config_key] = self.new(config_key) end end %w(mainnet testnet test).each do |config_key| define_method(config_key) do self[config_key] end end def [](config_key) configs[config_key] end def instance @instance ||= ( case Coinmux.env when 'production'; mainnet when 'development'; testnet when 'test'; test end) end def instance=(config) @instance = config end end def initialize(config_key) CONFIG[config_key].each do |key, value| self[key] = value end end def coin_join_uri coin_join_uris.first[1] end end
michaelgpearce/coinmux
lib/coinmux/coin_join_uri.rb
<gh_stars>10-100 class Coinmux::CoinJoinUri VALID_NETWORKS = %w(p2p filesystem test) attr_accessor :params, :application, :network class << self def parse(uri) match = uri.to_s.match(/coinjoin:\/\/([^\/]+)\/([^?]+)\??(.*)/) raise Coinmux::Error, "Could not parse URI" if match.nil? application = match[1] raise Coinmux::Error, "Invalid application #{application}. Must be coinmux" if application != 'coinmux' network = match[2] raise Coinmux::Error, "Invalid network #{network}. Must be one of #{VALID_NETWORKS.join(', ')}" unless VALID_NETWORKS.include?(network) query = match[3] query_params = query.split('&').inject({}) do |acc, key_and_value| key, value = key_and_value.split('=') acc[key] = value acc end new(:application => application, :network => network, :params => query_params) end end def initialize(attrs = {}) attrs = { application: "coinmux", network: "test", params: {} }.merge(attrs) attrs.each do |key, value| send("#{key}=", value) end end def to_s params_s = params.collect { |key, value| "#{key}=#{value}" }.join("&") "coinjoin://#{application}/#{network}#{params_s.blank? ? '' : "?#{params_s}"}" end def ==(other) return false unless other.is_a?(Coinmux::CoinJoinUri) return application == other.application && network == other.network && params == other.params end end
michaelgpearce/coinmux
lib/coinmux/state_machine/director.rb
class Coinmux::StateMachine::Director < Coinmux::StateMachine::Base STATES = %w(waiting_for_inputs waiting_for_outputs waiting_for_signatures failed completed) STATUS_UPDATE_INTERVAL = 60 def initialize(options = {}) assert_initialize_params!(options) super(options) self.coin_join_message = Coinmux::Message::CoinJoin.build(data_store, amount: options[:amount], participants: options[:participants]) self.state = 'waiting_for_inputs' end def start(&notification_callback) self.notification_callback = notification_callback start_coin_join end private def start_status_update next_status_update end def next_status_update event_queue.future_exec(STATUS_UPDATE_INTERVAL) do info("director doing status update") if !%w(failed completed).include?(state) status_message = coin_join_message.status.value insert_current_status_message(status_message.transaction_id) do next_status_update # do it again end end end end def insert_current_status_message(transaction_id = nil, &callback) status_message = coin_join_message.status.value if status_message.nil? || state != status_message.state new_status_message = Coinmux::Message::Status.build(coin_join_message, state: state, transaction_id: transaction_id) insert_message(:status, new_status_message) do yield if block_given? end else yield if block_given? end end def failure(error_identifier, error_message = nil) if state != 'failed' # already failed so don't cause infinite loop update_state('failed', message: "#{error_identifier}: #{error_message}") end end def start_coin_join notify(:inserting_coin_join_message) insert_coin_join_message(coin_join_message) do notify(:inserting_status_message) insert_current_status_message do start_waiting_for_inputs start_status_update end end end def start_waiting_for_inputs update_state_and_poll('waiting_for_inputs') do |&continue_poll| refresh_message(:inputs) do if coin_join_message.inputs.value.size >= coin_join_message.participants notify(:inserting_message_verification_message) insert_message(:message_verification, Coinmux::Message::MessageVerification.build(coin_join_message)) do start_waiting_for_outputs end else continue_poll.call end end end end def start_waiting_for_outputs update_state_and_poll('waiting_for_outputs') do |&continue_poll| refresh_message(:outputs) do if coin_join_message.outputs.value.size == coin_join_message.inputs.value.size inputs = coin_join_message.build_transaction_inputs outputs = coin_join_message.build_transaction_outputs notify(:inserting_transaction_message) insert_message(:transaction, Coinmux::Message::Transaction.build(coin_join_message, inputs: inputs, outputs: outputs)) do start_waiting_for_signatures end else continue_poll.call end end end end def start_waiting_for_signatures update_state_and_poll('waiting_for_signatures') do |&continue_poll| refresh_message(:transaction_signatures) do if coin_join_message.transaction_signatures.value.size == coin_join_message.transaction.value.inputs.size notify(:publishing_transaction) publish_transaction do |transaction_id| update_state('completed', transaction_id: transaction_id) end else continue_poll.call end end end end def update_state(state, options = {}, &block) info("director updating state to #{state}") self.state = state insert_current_status_message(options[:transaction_id]) do notify(state.to_sym, options) yield if block_given? end end def update_state_and_poll(state, transaction_id = nil, &block) update_state(state, transaction_id: transaction_id) do poll_for_state(state, &block) end end def poll_for_state(state, &block) event_queue.future_exec(MESSAGE_POLL_INTERVAL) do debug "director waiting for state change: #{state}" if self.state == state debug "director state not changed" block.call do # call again until state changes poll_for_state(state, &block) end end end end def publish_transaction(&callback) transaction = coin_join_message.transaction_object transaction_signatures = coin_join_message.transaction_signatures.value transaction_signatures = transaction_signatures.sort do |a, b| a.transaction_input_index <=> b.transaction_input_index end transaction_signatures.each_with_index do |transaction_signature, input_index| script_sig = Base64.decode64(transaction_signature.script_sig) begin bitcoin_network_facade.sign_transaction_input(transaction, input_index, script_sig) rescue Coinmux::Error => e yield Coinmux::Event.new(error: "Unable to sign transaction input: #{e}") return end end bitcoin_network_facade.post_transaction(transaction) do |event| handle_event(event, :unable_to_post_transaction) do yield(event.data) end end end def insert_coin_join_message(message, &callback) data_store.insert(data_store.coin_join_identifier, message.to_json) do |event| handle_event(event, :unable_to_insert_message) do yield end end end end
michaelgpearce/coinmux
lib/coinmux/cipher.rb
<filename>lib/coinmux/cipher.rb<gh_stars>10-100 class Coinmux::Cipher include Singleton, Coinmux::Facades def encrypt(secret_key, clear_text) cipher = build_cipher(:encrypt) cipher.key = digest_facade.digest(secret_key) cipher.iv = iv = cipher.random_iv # 16 bytes encrypted = cipher.update(clear_text) encrypted << cipher.final "#{iv}#{encrypted}" end def decrypt(secret_key, encrypted_text) cipher = build_cipher(:decrypt) cipher.key = digest_facade.digest(secret_key) cipher.iv = encrypted_text[0...16] # first 16 bytes are IV encrypted_text = encrypted_text[16..-1] # and decrypt it decrypted = cipher.update(encrypted_text) decrypted << cipher.final decrypted.to_s end private def build_cipher(type) OpenSSL::Cipher::Cipher.new("aes-256-cbc").tap do |cipher| cipher.send(type) end end end
michaelgpearce/coinmux
lib/coinmux/application/available_coin_joins.rb
<reponame>michaelgpearce/coinmux<filename>lib/coinmux/application/available_coin_joins.rb<gh_stars>10-100 require 'thread' class Coinmux::Application::AvailableCoinJoins include Coinmux::Facades, Coinmux::Threading attr_accessor :data_store def initialize(data_store) self.data_store = data_store end # Yields with a Coinmux::Event with Hash data: amount, total_participants, waiting_participants. def find(&callback) if block_given? do_find(&callback) else event = wait_for_callback(:do_find, &callback)[0] raise Coinmux::Error.new(event.error) if event.error event.data end end private def do_find(&callback) data_store.fetch_most_recent(data_store.coin_join_identifier, Coinmux::StateMachine::Participant::COIN_JOIN_MESSAGE_FETCH_SIZE) do |event| if event.error yield(event) else coin_join_messages = event.data.collect { |json| Coinmux::Message::CoinJoin.from_json(json, data_store, nil) }.compact available_coin_joins = [] if !coin_join_messages.empty? waiting_for = coin_join_messages.size waiting_for_mutex = Mutex.new coin_join_messages.each do |coin_join_message| coin_join_message.status.refresh do |event| if event.error yield(event) else if coin_join_message.status.try(:value).try(:state) != 'waiting_for_inputs' waiting_for_mutex.synchronize do waiting_for -= 1 end else coin_join_message.inputs.refresh do |event| if event.error yield(event) else waiting_for_mutex.synchronize do waiting_for -= 1 if coin_join_message.inputs.value.size < coin_join_message.participants available_coin_joins << { amount: coin_join_message.amount, total_participants: coin_join_message.participants, waiting_participants: coin_join_message.inputs.value.size } end end end end end end end end # we'll block until we get status/inputs for each message. not sure elegant async way to do this while waiting_for_mutex.synchronize { waiting_for > 0 } sleep(0.1) end end sorted = available_coin_joins.sort do |l, r| if (comp = l[:amount] <=> r[:amount]) == 0 if (comp = l[:total_participants] <=> r[:total_participants]) == 0 comp = l[:waiting_participants] <=> r[:waiting_participants] end end comp end debug("Available coin joins: #{sorted}") yield(Coinmux::Event.new(data: sorted)) end end end end
michaelgpearce/coinmux
lib/coinmux/bitcoin_util.rb
<filename>lib/coinmux/bitcoin_util.rb<gh_stars>10-100 module Coinmux::BitcoinUtil SATOSHIS_PER_BITCOIN = 100_000_000 DEFAULT_TRANSACTION_FEE = (0.0001 * SATOSHIS_PER_BITCOIN).to_i import 'com.google.bitcoin.core.NetworkParameters' def network_params Coinmux::Config.instance.bitcoin_network == 'mainnet' ? NetworkParameters.prodNet() : NetworkParameters.testNet3() end end
michaelgpearce/coinmux
spec/message/input_spec.rb
require 'spec_helper' describe Coinmux::Message::Input do before do fake_all_network_connections stub_bitcoin_network_for_coin_join(coin_join) end let(:template_message) { build(:coin_join_message, :with_inputs).inputs.value.detect(&:created_with_build) } let(:input_identifier) { template_message.input_identifier } let(:address) { template_message.address } let(:private_key) { template_message.private_key } let(:signature) { template_message.signature } let(:change_address) { template_message.change_address } let(:change_transaction_output_identifier) { template_message.change_transaction_output_identifier } let(:coin_join) { template_message.coin_join } describe "validations" do let(:message) do build(:input_message, address: address, private_key: private_key, signature: signature, change_address: change_address, change_transaction_output_identifier: change_transaction_output_identifier, coin_join: coin_join) end subject { message.valid? } it "is valid with default data" do subject expect(subject).to be_true end describe "#signature_correct" do context "with invalid signature" do let(:signature) { Base64.encode64('invalid').strip } it "is invalid" do expect(subject).to be_false expect(message.errors[:signature]).to include("is not correct for address #{address}") end end end describe "#change_address_valid" do context "with invalid change address" do let(:change_address) { "invalid_address" } it "is invalid" do expect(subject).to be_false expect(message.errors[:change_address]).to include("is not a valid address") end end end describe "#input_has_enough_value" do context "with not enough unspent value" do before do message.coin_join.should_receive(:input_has_enough_unspent_value?).with(address).and_return(false) end it "is invalid" do expect(subject).to be_false expect(message.errors[:address]).to include("does not have enough unspent value") end end end describe "#change_amount_not_more_than_transaction_fee_with_no_change_address" do context "with no change address" do let(:change_address) { nil } context "with unspent amount greater than coinjoin amount and participant transaction fee" do before do message.coin_join.should_receive(:unspent_value!).with(address).and_return(coin_join.amount + coin_join.participant_transaction_fee + 1) end it "is invalid" do expect(subject).to be_false expect(message.errors[:change_address]).to include("required for this input address") end end context "with unspent amount equal to coinjoin amount and participant transaction fee" do before do message.coin_join.should_receive(:unspent_value!).with(address).and_return(coin_join.amount + coin_join.participant_transaction_fee) end it "is valid" do expect(subject).to be_true end end end end end describe "#build" do subject { Coinmux::Message::Input.build(coin_join, private_key: private_key, change_address: change_address) } it "builds valid input" do expect(subject.valid?).to be_true end it "has private_key" do expect(subject.private_key).to eq(private_key) end it "has message_private_key and message_public_key for encrypting and decrypting" do message = "a random message #{rand}" encrypted_message = pki_facade.private_encrypt(subject.message_private_key, message) expect(pki_facade.public_decrypt(subject.message_public_key, encrypted_message)).to eq(message) end it "has change address" do expect(subject.change_address).to eq(change_address) end it "has random identifier for change_transaction_output_identifier" do expect(subject.change_transaction_output_identifier).to_not be_nil end end describe "#from_json" do let(:message) { template_message } let(:json) do { message_public_key: message.message_public_key, address: message.address, change_address: message.change_address, change_transaction_output_identifier: message.change_transaction_output_identifier, signature: message.signature }.to_json end subject do Coinmux::Message::Input.from_json(json, data_store, coin_join) end it "creates a valid input" do expect(subject).to_not be_nil expect(subject.valid?).to be_true expect(subject.message_public_key).to eq(message.message_public_key) expect(subject.address).to eq(message.address) expect(subject.change_address).to eq(message.change_address) end end end
michaelgpearce/coinmux
spec/spec_helper.rb
require File.join(File.dirname(__FILE__), '..', 'lib', 'coinmux') ENV['COINMUX_ENV'] = 'test' module Coinmux module Fake end end require 'rspec' # require 'spec/fake/application' require 'spec/fake/bitcoin_network' require 'factory_girl' require 'pry' FactoryGirl.find_definitions rescue puts "Warn: #{$!}" include Coinmux::BitcoinUtil, Coinmux::Facades # allow loading in console require 'rspec/mocks' RSpec::Mocks::setup(Object.new) def fake_all fake_bitcoin_network end def fake_all_network_connections fake_bitcoin_network end def fake_bitcoin_network @fake_bitcoin_network ||= Coinmux::Fake::BitcoinNetwork.new.tap do |bitcoin_network| Coinmux::BitcoinNetwork.stub(:instance).and_return(bitcoin_network) end end def stub_bitcoin_network_for_coin_join(coin_join) coin_join.stub(:transaction_object).and_return(double('transaction object double')) if !coin_join.inputs.value.empty? coin_join.inputs.value.each do |input| Coinmux::BitcoinNetwork.instance.stub(:unspent_inputs_for_address).with(input.address).and_return({ { id: "tx-#{input.address}", index: 123 } => 1234 * SATOSHIS_PER_BITCOIN }) end end if coin_join.transaction.value coin_join.transaction.value.inputs.each do |hash| address = hash['transaction_id'].split('-').last # we format the transaction id: "tx-address" change_address = coin_join.inputs.value.detect { |input| input.address == address }.change_address change_amount = coin_join.transaction.value.outputs.detect { |output| output['address'] == change_address }['amount'] tx_amount = coin_join.amount + change_amount + coin_join.participant_transaction_fee result = {}.tap do |result| key = {id: hash['transaction_id'], index: hash['output_index']} result[key] = tx_amount end Coinmux::BitcoinNetwork.instance.stub(:unspent_inputs_for_address).with(address).and_return(result) end coin_join.transaction.value.inputs.each_with_index do |input_hash, transaction_input_index| Coinmux::BitcoinNetwork.instance.stub(:build_transaction_input_script_sig).with(coin_join.transaction_object, transaction_input_index, "privkey-#{transaction_input_index}").and_return("scriptsig-#{transaction_input_index}") end end Coinmux::BitcoinNetwork.instance.stub(:transaction_input_unspent?).and_return(true) Coinmux::BitcoinNetwork.instance.stub(:script_sig_valid?).and_return(true) end def data_store Helper.data_store end def load_fixture(name) open(File.join(File.dirname(__FILE__), 'fixtures', name)) { |f| f.read } end module Helper class BitcoinInfo include Coinmux::Facades def initialize(index) @index = index end def [](key) send(key) end def private_key @private_key ||= "%064x" % @index end def public_key @public_key ||= bitcoin_crypto_facade.public_key_for_private_key!(private_key) end def address @address ||= bitcoin_crypto_facade.address_for_public_key!(public_key) end def identifier @identifier ||= "valid-identifier-#{@index}" end def signature @signature ||= bitcoin_crypto_facade.sign_message!(identifier, private_key) end end @@bitcoin_infos = [] @@bitcoin_info_index = 0 def self.next_bitcoin_info if (bitcoin_info = @@bitcoin_infos[@@bitcoin_info_index]).nil? @@bitcoin_infos << (bitcoin_info = ::Helper::BitcoinInfo.new(@@bitcoin_info_index + 1)) end @@bitcoin_info_index += 1 bitcoin_info end def self.bitcoin_info_for_address(address) @@bitcoin_infos.detect { |bitcoin_info| bitcoin_info[:address] == address } end def self.data_store @data_store ||= ( coin_join_uri = Coinmux::CoinJoinUri.parse(Coinmux::Config.instance.coin_join_uri) Coinmux::DataStore::Factory.build(coin_join_uri).tap do |data_store| data_store.connect {} end ) end end RSpec.configure do |config| config.include FactoryGirl::Syntax::Methods config.treat_symbols_as_metadata_keys_with_true_values = true config.run_all_when_everything_filtered = true config.filter_run :focus # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = 'random' config.before do Helper.data_store.clear Helper.class_variable_set(:@@bitcoin_info_index, 0) # start over reading bitcoin infos for each spec end end
michaelgpearce/coinmux
spec/message/association_spec.rb
require 'spec_helper' describe Coinmux::Message::Association do before do fake_all_network_connections end let(:template_message) { build(:association_message) } let(:created_with_build) { template_message.created_with_build } let(:name) { template_message.name } let(:type) { template_message.type } let(:read_only) { template_message.read_only } let(:data_store_identifier_from_build) { template_message.data_store_identifier_from_build } let(:data_store_identifier) { template_message.data_store_identifier } let(:coin_join) { build(:coin_join_message) } describe "validations" do let(:message) do build(:association_message, created_with_build: created_with_build, name: name, type: type, read_only: read_only, data_store_identifier_from_build: data_store_identifier_from_build, data_store_identifier: data_store_identifier, coin_join: coin_join) end subject { message.valid? } it "is valid with default data" do expect(subject).to be_true end describe "#data_store_identifier_has_correct_permissions" do let(:created_with_build) { false } context "when data_store_identifier does not allow requests" do before do Helper.data_store.stub(:identifier_can_request?).and_return(false) end it "is invalid" do expect(subject).to be_false expect(message.errors[:data_store_identifier]).to include("must allow requests") end end context "when not read only and data_store_identifier cannot insert" do let(:read_only) { false } before { Helper.data_store.stub(:identifier_can_insert?).and_return(false) } it "is invalid" do expect(subject).to be_false expect(message.errors[:data_store_identifier]).to include("must allow inserts") end end context "when not read only and data_store_identifier can insert" do let(:read_only) { false } before { Helper.data_store.stub(:identifier_can_insert?).and_return(true) } it "is valid" do expect(subject).to be_true end end end end describe "#build" do subject { Coinmux::Message::Association.build(coin_join, name: name, type: type, read_only: read_only) } it "builds valid input" do expect(subject.valid?).to be_true end it "has a data_store_identifier_from_build that can insert and request" do expect(Helper.data_store.identifier_can_insert?(subject.data_store_identifier_from_build)).to be_true expect(Helper.data_store.identifier_can_request?(subject.data_store_identifier_from_build)).to be_true end context "when read-only" do let(:read_only) { true } it "has a data_store_identifier that can only request" do expect(Helper.data_store.identifier_can_insert?(subject.data_store_identifier)).to be_false expect(Helper.data_store.identifier_can_request?(subject.data_store_identifier)).to be_true end end context "when not read-only" do let(:read_only) { false } it "has a data_store_identifier that can insert and request" do expect(Helper.data_store.identifier_can_insert?(subject.data_store_identifier)).to be_true expect(Helper.data_store.identifier_can_request?(subject.data_store_identifier)).to be_true end it "has same data_store_identifier_from_build and data_store_identifier" do expect(subject.data_store_identifier).to eq(subject.data_store_identifier_from_build) end end end describe "#from_data_store_identifier" do let(:message) { template_message } let(:data_store_identifier) { message.data_store_identifier } subject do Coinmux::Message::Association.from_data_store_identifier(data_store_identifier, coin_join, name, type, read_only) end it "creates a valid association" do expect(subject).to_not be_nil expect(subject.valid?).to be_true expect(subject.name).to eq(message.name) expect(subject.type).to eq(message.type) expect(subject.read_only).to eq(message.read_only) expect(subject.data_store_identifier).to eq(message.data_store_identifier) end end end
michaelgpearce/coinmux
lib/coinmux/message/transaction_signature.rb
class Coinmux::Message::TransactionSignature < Coinmux::Message::Base property :transaction_input_index, :script_sig, :message_verification validates :transaction_input_index, :script_sig, :message_verification, :presence => true validate :message_verification_correct, :if => :director? validate :transaction_input_index_valid validate :script_sig_valid class << self def build(coin_join, options = {}) options.assert_keys!(required: [:transaction_input_index, :private_key]) message = super(coin_join.data_store, coin_join) message.transaction_input_index = options[:transaction_input_index] script_sig = Coinmux::BitcoinNetwork.instance.build_transaction_input_script_sig( coin_join.transaction_object, options[:transaction_input_index], options[:private_key]) message.script_sig = Base64.encode64(script_sig) message.message_verification = coin_join.build_message_verification( :transaction_signature, options[:transaction_input_index], script_sig) message end end private def transaction_input_index_valid return unless errors[:transaction_input_index].empty? unless bitcoin_network_facade.transaction_input_unspent?(coin_join.transaction_object, transaction_input_index) errors[:transaction_input_index] << "has been spent" end end def script_sig_valid return unless errors[:script_sig].empty? unless bitcoin_network_facade.script_sig_valid?(coin_join.transaction_object, transaction_input_index, Base64.decode64(script_sig)) errors[:script_sig] << "is not valid" end end def message_verification_correct return unless errors[:message_verification].empty? unless coin_join.message_verification_valid?(:transaction_signature, message_verification, transaction_input_index, Base64.decode64(script_sig)) errors[:message_verification] << "cannot be verified" end end end
michaelgpearce/coinmux
lib/coinmux/state_machine/event.rb
<reponame>michaelgpearce/coinmux class Coinmux::StateMachine::Event attr_accessor :source, :type, :options def initialize(params = {}) params.each do |key, value| send("#{key}=", value) end end end
michaelgpearce/coinmux
lib/coinmux/message/transaction.rb
class Coinmux::Message::Transaction < Coinmux::Message::Base property :inputs, :outputs validate :inputs_is_array_of_hashes validate :outputs_is_array_of_hashes validate :has_minimum_number_of_coin_join_amount_outputs validate :has_no_duplicate_inputs validate :has_no_duplicate_outputs validate :has_correct_participant_inputs, :unless => :created_with_build? validate :has_correct_participant_outputs, :unless => :created_with_build? class << self def build(coin_join, options = {}) options.assert_keys!(required: [:inputs, :outputs]) message = super(coin_join.data_store, coin_join) message.inputs = options[:inputs] message.outputs = options[:outputs] message end end def participant_input @participant_input ||= coin_join.inputs.value.detect(&:created_with_build?) end def participant_output @participant_output ||= coin_join.outputs.value.detect(&:created_with_build?) end def participant_input_transactions @participant_input_transactions ||= coin_join.unspent_transaction_inputs(participant_input.address) end def participant_input_amount @participant_input_amount ||= participant_input_transactions.collect { |hash| hash[:amount] }.inject(&:+) end def participant_change_amount @participant_change_amount ||= participant_input_amount - coin_join.amount - coin_join.participant_transaction_fee end private def inputs_is_array_of_hashes array_of_hashes_is_valid(inputs, :inputs, 'address', 'transaction_id', 'output_index') end def outputs_is_array_of_hashes array_of_hashes_is_valid(outputs, :outputs, 'address', 'amount', 'identifier') end def array_of_hashes_is_valid(array, property, *required_keys) (errors[property] << "is not an array" and return) unless array.is_a?(Array) array.each do |element| (errors[property] << "is not a hash" and return) unless element.is_a?(Hash) (errors[property] << "does not have correct keys" and return) unless required_keys.sort == element.keys.sort end end def has_minimum_number_of_coin_join_amount_outputs return unless errors[:outputs].empty? if outputs.select { |output| output['amount'] == coin_join.amount }.size < coin_join.participants errors[:outputs] << "does not have enough participants" end end def has_no_duplicate_inputs return unless errors[:inputs].empty? if inputs.uniq.size != inputs.size errors[:inputs] << "has a duplicate input" end end def has_no_duplicate_outputs return unless errors[:outputs].empty? if outputs.collect { |output| [output['address'], output['identifier']] }.uniq.size != outputs.size errors[:outputs] << "has a duplicate output" end end def has_correct_participant_inputs return unless errors[:inputs].empty? # every one of the participant transactions must be specified, these are the only transactions participant will sign participant_input_transactions.each do |p_tx| if inputs.detect { |input| input['transaction_id'] == p_tx[:id] && input['output_index'] == p_tx[:index] }.nil? errors[:inputs] << "does not contain transaction #{p_tx[:id]}:#{p_tx[:index]}" return end end end def has_correct_participant_outputs return unless errors[:outputs].empty? if !output_exists?(participant_output.address, coin_join.amount, participant_output.transaction_output_identifier) errors[:outputs] << "does not have output to #{participant_output.address} for #{coin_join.amount}" return end if participant_input.change_address.nil? # this shouldn't ever happen here, but let's make sure we don't send any change as miner fees if participant_change_amount != 0 errors[:outputs] << "has no change address for amount #{participant_change_amount}" return end else if !output_exists?(participant_input.change_address, participant_change_amount, participant_input.change_transaction_output_identifier) errors[:outputs] << "does not have output to #{participant_input.change_address} for #{participant_change_amount}" return end end end def output_exists?(address, amount, identifier) !!outputs.detect { |output| output['address'] == address && output['amount'] == amount && output['identifier'] == identifier } end end
michaelgpearce/coinmux
lib/coinmux/bitcoin_crypto.rb
class Coinmux::BitcoinCrypto include Singleton, Coinmux::BitcoinUtil import 'java.math.BigInteger' import 'java.security.SignatureException' import 'com.google.bitcoin.core.AddressFormatException' import 'com.google.bitcoin.core.ECKey' import 'com.google.bitcoin.core.Address' import 'com.google.bitcoin.core.DumpedPrivateKey' import 'com.google.bitcoin.core.Utils' import 'com.google.bitcoin.core.NetworkParameters' import 'org.spongycastle.util.encoders.Hex' # https://github.com/jruby/jruby/wiki/UnlimitedStrengthCrypto begin java.lang.Class.for_name('javax.crypto.JceSecurity').get_declared_field('isRestricted').tap{|f| f.accessible = true; f.set nil, false} rescue Exception => e end class << self def def_no_raise_method(method, raise_return_value) define_method(method) do |*args| begin send("#{method}!", *args) rescue Coinmux::Error raise_return_value end end end end def verify_message!(message, signature_base_64, address) address == ECKey.signedMessageToKey(message, signature_base_64).toAddress(network_params).to_s rescue => e raise Coinmux::Error, "Message cannot be verified: #{e}" end def_no_raise_method(:verify_message, false) def sign_message!(message, private_key_hex) build_ec_key(private_key_hex).signMessage(message) rescue => e raise Coinmux::Error, "Message cannot be signed: #{e}" end def_no_raise_method(:sign_message, nil) def public_key_for_private_key!(private_key_hex) Hex.encode(build_ec_key(private_key_hex).getPubKey()).to_s.upcase rescue => e raise Coinmux::Error, "Cannot get public key from private key" # do not show private key end def_no_raise_method(:public_key_for_private_key, nil) def address_for_public_key!(public_key_hex) Address.new(network_params, Utils.sha256hash160(Hex.decode(public_key_hex))).to_s rescue => e raise Coinmux::Error, "Message cannot be signed: #{e}" end def_no_raise_method(:address_for_public_key, nil) def address_for_private_key!(private_key_hex) address_for_public_key!(public_key_for_private_key!(private_key_hex)) end def_no_raise_method(:address_for_private_key, nil) def verify_address!(address) Address.new(network_params, address) true rescue => e raise Coinmux::Error, "Address not valid: #{e}" end def_no_raise_method(:verify_address, false) def private_key_to_hex!(data) return data if data.size == 64 private_key_hex = begin Utils.bytesToHexString(DumpedPrivateKey.new(network_params, data).getKey().getPrivKeyBytes()) rescue AddressFormatException => e nil end raise Coinmux::Error, "Private Key not valid" if private_key_hex.nil? private_key_hex.upcase end def_no_raise_method(:private_key_to_hex, nil) private def build_ec_key(private_key_hex) ECKey.new(BigInteger.new(private_key_hex, 16)) end end
michaelgpearce/coinmux
lib/coinmux/application/mixer.rb
<reponame>michaelgpearce/coinmux<filename>lib/coinmux/application/mixer.rb class Coinmux::Application::Mixer include Coinmux::Facades ATTRS = [:event_queue, :data_store, :amount, :participants, :input_private_key, :output_address, :change_address] attr_accessor *ATTRS attr_accessor :participant, :director, :notification_callback def initialize(attributes) attributes.assert_keys!(required: ATTRS) attributes.each do |key, value| send("#{key}=", value) end end def start(&callback) self.notification_callback = callback self.participant = build_participant participant.start(&mixer_callback) end def cancel(&callback) if !%w(failed completed).include?(director.try(:coin_join_message).try(:state).try(:value).try(:state)) director.coin_join_message.status.insert(Coinmux::Message::Status.build(director.coin_join_message, state: 'failed')) do yield if block_given? end else yield if block_given? end end private def notify_event(event) notification_callback.call(event) end def build_participant Coinmux::StateMachine::Participant.new( event_queue: event_queue, data_store: data_store, amount: amount, participants: participants, input_private_key: input_private_key, output_address: output_address, change_address: change_address) end def build_director Coinmux::StateMachine::Director.new( event_queue: event_queue, data_store: data_store, amount: amount, participants: participants) end def mixer_callback @mixer_callback ||= Proc.new do |event| debug "event queue event received: #{event.inspect}" notify_event(event) if event.type == :failed self.director = self.participant = nil # end execution else if event.source == :participant handle_participant_event(event) elsif event.source == :director handle_director_event(event) else raise "Unknown event source: #{event.source}" end end # nothing left to do notify_event(Coinmux::StateMachine::Event.new(source: :mixer, type: :done)) if participant.nil? && director.nil? end end def handle_participant_event(event) if [:no_available_coin_join].include?(event.type) if director.nil? # start our own Director since we couldn't find one self.director = build_director director.start(&mixer_callback) end elsif [:input_not_selected, :transaction_not_found].include?(event.type) # TODO: try again elsif event.type == :completed self.participant = nil # done elsif event.type == :failed self.participant = nil # done end end def handle_director_event(event) if event.type == :waiting_for_inputs # our Director is now ready, so let's get started with a new participant self.participant = build_participant participant.start(&mixer_callback) elsif event.type == :failed || event.type == :completed self.director = nil # done end end end
michaelgpearce/coinmux
lib/coinmux/message/association.rb
class Coinmux::Message::Association < Coinmux::Message::Base attr_accessor :name, :type, :data_store_identifier_from_build, :data_store_identifier, :read_only validate :data_store_identifier_has_correct_permissions, :unless => :created_with_build? class << self def build(coin_join, options = {}) options.assert_keys!(required: [:name, :type, :read_only]) message = build_without_associations(coin_join.data_store, coin_join) message.name = options[:name].to_s message.type = options[:type] message.read_only = options[:read_only] message.data_store_identifier_from_build = coin_join.data_store.generate_identifier message.data_store_identifier = options[:read_only] ? coin_join.data_store.convert_to_request_only_identifier(message.data_store_identifier_from_build) : message.data_store_identifier_from_build message end def from_data_store_identifier(data_store_identifier, coin_join, name, type, read_only) message = new message.data_store = coin_join.data_store message.coin_join = coin_join message.name = name.to_s message.type = type message.read_only = read_only message.data_store_identifier = data_store_identifier if !message.valid? debug "Association message #{name} is not valid: #{message.errors.full_messages}" return nil end message end end def initialize # Note: a set is ordered in Ruby, but there is no guarantee of ordering of the messages # For :fixed and :variable associations, we rely on the datastore returning the correct first/last inserted message @data_store_messages = Set.new @inserted_messages = Set.new end def value result = if type == :list messages elsif type == :fixed messages.first elsif type == :variable messages.first # note: we do a "fetch_last" from data_store facade so there is only ever one message else raise "Unexpected type: #{type.inspect}" end result end # A combination of the inserted messages and the fetched data_store messages from invocations of refresh. # The inserted messages are chosen over those from the data store since they may have additional data (keys, etc) def messages result = if type == :list @inserted_messages + @data_store_messages # Set arithmetic will choose inserted over data_store elsif type == :fixed || type == :variable @inserted_messages.empty? ? @data_store_messages : @inserted_messages # if we inserted it, use it end result.to_a end def insert(message, &callback) @inserted_messages << message data_store.insert(data_store_identifier_from_build || data_store_identifier, message.to_json) do |event| yield(event) if block_given? end end def refresh(&callback) methods = { list: :fetch_all, fixed: :fetch_first, variable: :fetch_last } fetch_messages(methods[type]) do |event| if event.error yield(event) else @data_store_messages.clear @data_store_messages += event.data yield(Coinmux::Event.new(data: messages)) end end end private def fetch_messages(method, &callback) data_store.send(method, data_store_identifier) do |event| if event.error yield(event) else messages = if event.data.nil? [] elsif method == :fetch_all event.data.collect { |data| association_class.from_json(data, data_store, coin_join) } elsif method == :fetch_first || method == :fetch_last [association_class.from_json(event.data, data_store, coin_join)] end # ignore bad data returned by #from_json as nil with compact messages.compact! yield(Coinmux::Event.new(data: messages)) end end end def data_store_identifier_has_correct_permissions can_insert = data_store.identifier_can_insert?(data_store_identifier.to_s) can_request = data_store.identifier_can_request?(data_store_identifier.to_s) errors[:data_store_identifier] << "must allow requests" unless can_request if !read_only errors[:data_store_identifier] << "must allow inserts" if !can_insert end end def association_class Coinmux::Message.const_get(name.classify) end def build_message(json) association_class.from_json(json, data_store, coin_join) end end
michaelgpearce/coinmux
spec/message/message_verification_spec.rb
<filename>spec/message/message_verification_spec.rb require 'spec_helper' describe Coinmux::Message::MessageVerification do before do fake_all_network_connections end let(:coin_join) { build(:coin_join_message, :with_inputs) } let(:template_message) { Coinmux::Message::MessageVerification.build(coin_join) } let(:encrypted_message_identifier) { template_message.encrypted_message_identifier } let(:encrypted_secret_keys) { template_message.encrypted_secret_keys } let(:message) do Coinmux::Message::MessageVerification.new( coin_join: coin_join, encrypted_message_identifier: encrypted_message_identifier, encrypted_secret_keys: encrypted_secret_keys) end describe "validations" do subject { message.valid? } it "is valid with default data" do subject expect(subject).to be_true end describe "#ensure_owned_input_can_decrypt_message_identifier" do context "with no invalid encrypted secret key" do before do message.encrypted_secret_keys.keys.each do |address| message.encrypted_secret_keys[address] = "invalid encoding" end end it "is invalid" do subject expect(message.errors[:encrypted_secret_keys]).to include("cannot be decrypted") end end end describe "#ensure_has_addresses_for_all_encrypted_secret_keys" do context "with unknown encrypted_secret_keys address" do before do message.encrypted_secret_keys[:unknown_address] = "should be here" end it "is invalid" do subject expect(message.errors[:encrypted_secret_keys]).to include("contains address not an input") end end end describe "#ensure_encrypted_secret_keys_size_is_participant_count" do context "with incorrect number of participants" do before do coin_join.participants += 1 end it "is invalid" do subject expect(message.errors[:encrypted_secret_keys]).to include("does not match number of participants") end end end end describe "#get_secret_key_for_address!" do let(:message) { template_message } let(:input) { coin_join.inputs.value.first } let(:address) { input.address } subject { message.get_secret_key_for_address!(address) } context "with valid data" do it "returns the secret key for the address" do expect(subject).to eq(message.secret_key) end end context "with no matching address" do before do message.encrypted_secret_keys = {} end it "raises ArgumentError" do expect { subject }.to raise_error(ArgumentError, "not found for address #{address}") end end context "with encrypted_secret_keys incorrectly encoded" do before do message.encrypted_secret_keys[address] = "not-base-64" end it "raises ArgumentError" do expect { subject }.to raise_error(ArgumentError, "cannot be decrypted") end end context "with encrypted_secret_keys with invalid key" do before do message.encrypted_secret_keys[address] = Base64.encode64("incorrect key") end it "raises ArgumentError" do expect { subject }.to raise_error(ArgumentError, "cannot be decrypted") end end end describe "#build" do subject { Coinmux::Message::MessageVerification.build(coin_join) } it "builds valid message verification" do input = subject expect(input.valid?).to be_true end end describe "#from_json" do let(:message) { Coinmux::Message::MessageVerification.build(coin_join) } let(:json) do { encrypted_message_identifier: message.encrypted_message_identifier, encrypted_secret_keys: message.encrypted_secret_keys }.to_json end subject do Coinmux::Message::MessageVerification.from_json(json, data_store, coin_join) end it "creates a valid message verification" do expect(subject).to_not be_nil expect(subject.valid?).to be_true expect(subject.encrypted_message_identifier).to eq(message.encrypted_message_identifier) expect(subject.encrypted_secret_keys).to eq(message.encrypted_secret_keys) end end end
michaelgpearce/coinmux
lib/coinmux/message/output.rb
<reponame>michaelgpearce/coinmux class Coinmux::Message::Output < Coinmux::Message::Base property :address, :message_verification, :transaction_output_identifier validates :address, :message_verification, :transaction_output_identifier, :presence => true validate :message_verification_correct, :if => :message_verification validate :address_valid, :if => :address class << self def build(coin_join, options = {}) options.assert_keys!(required: :address) message = super(coin_join.data_store, coin_join) message.address = options[:address] message.transaction_output_identifier = digest_facade.random_identifier message.message_verification = message.build_message_verification message end end def build_message_verification coin_join.build_message_verification(:output, address) end private def message_verification_correct return unless director? # only the director can validate these messages; participants wait for transaction message unless coin_join.message_verification_valid?(:output, message_verification, address) errors[:message_verification] << "cannot be verified" end end def address_valid return if errors[:address].present? unless bitcoin_crypto_facade.verify_address(address) errors[:address] << "is not a valid address" end end end
michaelgpearce/coinmux
spec/message/status_spec.rb
require 'spec_helper' describe Coinmux::Message::Status do before do fake_all_network_connections end let(:template_message) { build(:status_message) } let(:state) { template_message.state } let(:transaction_id) { template_message.transaction_id } let(:coin_join) { template_message.coin_join } describe "validations" do let(:message) { build(:status_message, state: state, transaction_id: transaction_id) } subject { message.valid? } it "is valid with default data" do expect(subject).to be_true end describe "#transaction_id" do context "when present" do context "with completed state" do let(:state) { 'completed' } it "is valid" do expect(subject).to be_true end end (Coinmux::StateMachine::Director::STATES - ['completed']).each do |test_state| context "with #{test_state} state" do let(:state) { test_state } it "is invalid" do expect(subject).to be_false expect(message.errors[:transaction_id]).to include("must not be present for state #{test_state}") end end end end context "when nil" do let(:transaction_id) { nil } context "with completed state" do let(:state) { 'completed' } it "is invalid" do expect(subject).to be_false expect(message.errors[:transaction_id]).to include("must be present for state completed") end end (Coinmux::StateMachine::Director::STATES - ['completed']).each do |test_state| context "with #{test_state} state" do let(:state) { test_state } it "is valid" do expect(subject).to be_true end end end end end describe "#state_valid" do context "when state is invalid" do let(:state) { 'InvalidState' } it "is invalid" do expect(subject).to be_false expect(message.errors[:state]).to include("is not a valid state") end end end end describe "#build" do subject { Coinmux::Message::Status.build(coin_join, state: state, transaction_id: transaction_id) } it "builds valid status" do expect(subject.valid?).to be_true end end describe "#from_json" do let(:message) { template_message } let(:json) do { state: message.state, transaction_id: message.transaction_id, }.to_json end subject do Coinmux::Message::Status.from_json(json, data_store, coin_join) end it "creates a valid status" do expect(subject).to_not be_nil expect(subject.valid?).to be_true expect(subject.state).to eq(message.state) expect(subject.transaction_id).to eq(message.transaction_id) end end end
michaelgpearce/coinmux
gui/view/base.rb
<reponame>michaelgpearce/coinmux class Gui::View::Base include Coinmux::BitcoinUtil, Coinmux::Facades attr_accessor :application, :root_panel, :primary_button import 'java.awt.Dimension' import 'java.awt.Font' import 'java.awt.FlowLayout' import 'java.awt.GridBagLayout' import 'java.awt.GridBagConstraints' import 'java.awt.GridLayout' import 'java.awt.Insets' import 'javax.swing.BorderFactory' import 'javax.swing.BoxLayout' import 'javax.swing.ImageIcon' import 'javax.swing.JButton' import 'javax.swing.JLabel' import 'javax.swing.JPanel' import 'javax.swing.JSeparator' def initialize(application, root_panel) @application = application @root_panel = root_panel root_panel.add(container) end def add handle_add JPanel.new(GridBagLayout.new).tap do |container| container.add(about_button, build_grid_bag_constraints(fill: :none, anchor: :east)) footer.add(container, build_grid_bag_constraints(fill: :horizontal)) end end # subclasses should not override, override handle_show instead def show root_panel.getRootPane().setDefaultButton(primary_button) handle_show end def update show end protected def handle_show # override in subclass end def handle_add # override in subclass end def add_header(text, options = {}) label = JLabel.new(text, JLabel::CENTER) label.setFont(Font.new(label.getFont().getName(), Font::BOLD, 24)) header.add(label, build_grid_bag_constraints(fill: :horizontal, anchor: :center)) if options[:show_settings] header.add(settings_button, build_grid_bag_constraints( gridx: 1, fill: :none, weightx: 0.00000001, anchor: :east)) end end def add_row(&block) yield(body) end def add_button_row(primary_button, secondary_button = nil) container = JPanel.new container.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0)) container.setLayout(GridLayout.new(0, 1)) buttons.add(container, build_grid_bag_constraints(fill: :horizontal)) container.add(JSeparator.new) panel = JPanel.new panel.setLayout(FlowLayout.new(FlowLayout::CENTER, 0, 0)) container.add(panel) buttons = [primary_button, secondary_button].compact self.primary_button = buttons.first buttons.reverse! if Coinmux.os == :macosx buttons.each do |button| panel.add(button) end end def add_form_row(label_text, component, index, options = {}) options = { last: false, width: nil, label_width: 180 }.merge(options) add_row do |parent| # parent.add(panel, build_grid_bag_constraints(gridy: 1, fill: :both, anchor: :center, weighty: 1000000)) container = JPanel.new container.setLayout(BoxLayout.new(container, BoxLayout::LINE_AXIS)) parent.add(container, build_grid_bag_constraints( fill: options[:last] ? :horizontal : :horizontal, weighty: options[:last] ? 1000000 : 0, anchor: :north, insets: Insets.new(0, 0, 10, 0), gridy: index)) label = JLabel.new(label_text, JLabel::RIGHT) label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20)) label.setToolTipText(options[:tool_tip]) if options[:tool_tip] label.setPreferredSize(Dimension.new(options[:label_width], 0)) container.add(label) if options[:width] component_container = JPanel.new(GridBagLayout.new) component_container.add(component, build_grid_bag_constraints(fill: :vertical, anchor: :west)) component.setPreferredSize(Dimension.new(options[:width], component.getPreferredSize().height)) container.add(component_container) else container.add(component) end end end def build_grid_bag_constraints(attributes) attributes = { gridx: 0, gridy: 0, gridwidth: 1, gridheight: 1, ipadx: 0, ipady: 0, weightx: 1.0, weighty: 1.0, fill: :both, anchor: :center }.merge(attributes) GridBagConstraints.new.tap do |c| attributes.each do |key, value| c.send("#{key}=", value.is_a?(Symbol) ? GridBagConstraints.const_get(value.to_s.upcase) : value) end end end private def container @container ||= JPanel.new(GridBagLayout.new) end def header @header ||= JPanel.new(GridBagLayout.new).tap do |header| container.add(header, build_grid_bag_constraints( gridy: 0, fill: :horizontal, insets: Insets.new(0, 0, 10, 0), anchor: :north)) end end def body @body ||= JPanel.new(GridBagLayout.new).tap do |body| container.add(body, build_grid_bag_constraints( gridy: 1, weighty: 1000000, # take up all space with body fill: :both, anchor: :center)) end end def buttons @buttons ||= JPanel.new(GridBagLayout.new).tap do |buttons| container.add(buttons, build_grid_bag_constraints( gridy: 2, fill: :horizontal, anchor: :south)) end end def footer @footer ||= JPanel.new(GridBagLayout.new).tap do |footer| container.add(footer, build_grid_bag_constraints( gridy: 3, insets: Insets.new(10, 0, 0, 0), fill: :horizontal, anchor: :south)) end end def settings_button_icon @settings_button_icon ||= ImageIcon.new(Coinmux::FileUtil.read_content_as_java_bytes('gui', 'assets', 'settings_24.png')) end def settings_button @settings_button ||= Gui::Component::LinkButton.new.tap do |settings_button| settings_button.setIcon(settings_button_icon) settings_button.addActionListener() do |e| application.show_preferences end end end def about_button @about_button ||= Gui::Component::LinkButton.new("About Coinmux").tap do |button| button.addActionListener() do |e| application.show_about end end end end
michaelgpearce/coinmux
gui/event_queue.rb
<gh_stars>10-100 class Gui::EventQueue include Singleton import 'javax.swing.SwingUtilities' import 'javax.swing.Timer' def sync_exec(&callback) if SwingUtilities.isEventDispatchThread() yield else SwingUtilities.invokeAndWait(create_callback_with_error_handling(&callback)) end end def future_exec(seconds = 0, &callback) if seconds <= 0 SwingUtilities.invokeLater(create_callback_with_error_handling(&callback)) else Timer.new(seconds * 1000, lambda { |e| create_callback_with_error_handling(&callback).call }).tap do |timer| timer.setRepeats(false) timer.start() end end end private def create_callback_with_error_handling(&callback) Proc.new do begin yield rescue Exception => e puts "Unhandled error in event dispatch thread: #{e}", *e.backtrace end end end end
michaelgpearce/coinmux
lib/coinmux/message/coin_join.rb
class Coinmux::Message::CoinJoin < Coinmux::Message::Base include Coinmux::BitcoinUtil VERSION = 1 DEFAULT_AMOUNT = 1 * SATOSHIS_PER_BITCOIN DEFAULT_PARTICIPANTS = 5 property :version, :identifier, :message_public_key, :amount, :participants, :participant_transaction_fee add_association :inputs, :list, :read_only => false add_association :outputs, :list, :read_only => false add_association :message_verification, :fixed, :read_only => true add_association :transaction, :fixed, :read_only => true add_association :transaction_signatures, :list, :read_only => false add_association :status, :variable, :read_only => true attr_accessor :message_private_key validates :version, :identifier, :message_public_key, :amount, :participants, :participant_transaction_fee, :presence => true validate :participants_numericality, :if => :participants validate :amount_numericality, :if => :amount validate :participant_transaction_fee_numericality, :if => :participant_transaction_fee validate :version_matches, :if => :version class << self def build(data_store, options = {}) options.assert_keys!(optional: [:amount, :participants, :participant_transaction_fee]) message = super(data_store, nil) message.version = VERSION message.identifier = digest_facade.random_identifier message.message_private_key, message.message_public_key = pki_facade.generate_keypair message.amount = options[:amount].try(:to_i) || DEFAULT_AMOUNT message.participants = options[:participants].try(:to_i) || DEFAULT_PARTICIPANTS message.participant_transaction_fee = message.participants == 0 ? 0 : options[:participant_transaction_fee] || (Coinmux::BitcoinUtil::DEFAULT_TRANSACTION_FEE / message.participants).to_i message end end def build_message_verification(prefix, *keys) return nil unless input = inputs.value.detect(&:created_with_build?) return nil if message_verification.value.nil? encoded_secret_message_key = message_verification.value.encrypted_secret_keys[input.address] encrypted_secret_message_key = Base64.decode64(encoded_secret_message_key) message_private_key = input.message_private_key return nil unless secret_message_key = pki_facade.private_decrypt(message_private_key, encrypted_secret_message_key) return nil unless message_identifier = cipher_facade.decrypt( secret_message_key, Base64.decode64(message_verification.value.encrypted_message_identifier)) digest_facade.hex_message_digest(prefix, message_identifier, *keys) end def message_verification_valid?(prefix, message_verification, *keys) raise ArgumentError, "Only director can check message verification validity" unless director? message_verification == digest_facade.hex_message_digest(prefix, self.message_verification.value.message_identifier, *keys) end def director? coin_join.nil? end def build_transaction_inputs raise ArgumentError, "cannot be invoked until all inputs and outputs present" unless ready_to_build_transaction? raise ArgumentError, "cannot be called unless director" unless director? inputs.value.inject([]) do |acc, input| acc += unspent_transaction_inputs(input.address).collect do |tx_input| { 'address' => input.address, 'transaction_id' => tx_input[:id], 'output_index' => tx_input[:index] } end acc end end def build_transaction_outputs raise ArgumentError, "cannot be invoked until all inputs and outputs present" unless ready_to_build_transaction? raise ArgumentError, "cannot be called unless director" unless director? [].tap do |result| result.concat(outputs.value.collect do |output| { 'address' => output.address, 'amount' => amount, 'identifier' => output.transaction_output_identifier } end) result.concat(inputs.value.select(&:change_address).collect do |input| unspent_input_amount = unspent_value!(input.address) change_amount = unspent_input_amount - amount - participant_transaction_fee { 'address' => input.change_address, 'amount' => change_amount, 'identifier' => input.change_transaction_output_identifier } end) end end def ready_to_build_transaction? # Note that all outputs have been verified as being associated to an unknown input inputs.value.size >= participants && outputs.value.size == inputs.value.size end def transaction_object raise ArgumentError, "cannot be invoked unless transaction present" if transaction.value.nil? @transaction_object ||= ( # Note: we never call this function until we have finalized the transaction inputs/outs with the transaction message inputs = transaction.value.inputs.collect { |input| { id: input['transaction_id'], index: input['output_index'] } } outputs = transaction.value.outputs.collect { |output| { address: output['address'], amount: output['amount'] } } bitcoin_network_facade.build_unsigned_transaction(inputs, outputs) ) end def unspent_value!(address) unspent_transaction_inputs(address).collect { |hash| hash[:amount] }.inject(&:+) end def input_has_enough_unspent_value?(address) begin unspent_transaction_inputs(address) true rescue Coinmux::Error => e false end end # Retrieves the inputs used to for the coinjoin. # @address [String] Participant address. # @return [Array] Array of hashes with `:id` (transaction hash identifier), `:index` (the index of the transaction output that is unspent) and `:amount` (the unspent amount) sorted from largest amount to smallest amount. # @raise [Coinmux::Error] Unable to retrieve inputs or input data invalid def unspent_transaction_inputs(address) @unspent_transaction_inputs_hash ||= {} if (inputs = @unspent_transaction_inputs_hash[address]).nil? inputs = retrieve_unspent_transaction_inputs(bitcoin_network_facade.unspent_inputs_for_address(address), amount + participant_transaction_fee) @unspent_transaction_inputs_hash[address] = inputs end inputs end def retrieve_unspent_transaction_inputs(unspent_inputs, minimum_amount) total_amount = unspent_inputs.values.reduce(&:+) || 0 raise Coinmux::Error, "does not have #{minimum_amount} unspent" if total_amount < minimum_amount inputs = unspent_inputs.collect do |key, amount| { id: key[:id], index: key[:index], amount: amount } end.sort do |left, right| result = right[:amount] <=> left[:amount] result = right[:id] <=> left[:id] if result == 0 # ensure always sort the same way when amounts are equal result end inputs end private def version_matches (errors[:version] << "must be #{VERSION}" and return) unless version.to_s == VERSION.to_s end def participants_numericality (errors[:participants] << "is not an integer" and return) unless participants.to_s.to_i == participants (errors[:participants] << "must be at least 2" and return) unless participants > 1 end def amount_numericality (errors[:amount] << "is not a decimal number" and return) unless amount.to_s.to_f == amount (errors[:amount] << "must be greater than 0" and return) unless amount > 0 end def participant_transaction_fee_numericality (errors[:participant_transaction_fee] << "is not an integer" and return) unless participant_transaction_fee.to_s.to_i == participant_transaction_fee (errors[:participant_transaction_fee] << "may not be a negative amount" and return) if participant_transaction_fee < 0 (errors[:participant_transaction_fee] << "may not be greater than #{DEFAULT_TRANSACTION_FEE}" and return) if participant_transaction_fee > DEFAULT_TRANSACTION_FEE end end
michaelgpearce/coinmux
lib/coinmux/state_machine/participant.rb
class Coinmux::StateMachine::Participant < Coinmux::StateMachine::Base attr_accessor :input_private_key, :input_address, :output_address, :change_address STATE = %w(finding_available_coin_join failed completed) COIN_JOIN_MESSAGE_FETCH_SIZE = 50 def initialize(options = {}) assert_initialize_params!(options, required: [:input_private_key, :output_address, :change_address]) super(options) self.input_private_key = options[:input_private_key] self.input_address = bitcoin_crypto_facade.address_for_private_key!(options[:input_private_key]) self.output_address = options[:output_address] self.change_address = options[:change_address] self.state = 'finding_coin_join' end def start(&notification_callback) self.notification_callback = notification_callback start_finding_coin_join end private def start_finding_coin_join notify(:finding_coin_join_message) fetch_available_coin_join_message do |coin_join_message| if coin_join_message.nil? notify(:no_available_coin_join) else self.coin_join_message = coin_join_message start_inserting_input end end end def start_inserting_input notify(:inserting_input) insert_message(:inputs, Coinmux::Message::Input.build(coin_join_message, private_key: input_private_key, change_address: change_address)) do notify(:waiting_for_other_inputs) wait_for_state('waiting_for_outputs') do refresh_message(:inputs) do refresh_message(:message_verification) do if coin_join_message.message_verification.value.nil? # unable to validate message, so we were not part of it failure(:input_not_selected) else start_inserting_output end end end end end end def start_inserting_output notify(:inserting_output) insert_message(:outputs, Coinmux::Message::Output.build(coin_join_message, address: output_address)) do notify(:waiting_for_other_outputs) wait_for_state('waiting_for_signatures') do refresh_message(:outputs) do refresh_message(:transaction) do if coin_join_message.transaction.value.nil? failure(:transaction_not_found) else start_inserting_transaction_signatures end end end end end end def start_inserting_transaction_signatures notify(:inserting_transaction_signatures) insert_transaction_signature(0, coin_join_message.transaction.value.inputs.dup) end def insert_transaction_signature(transaction_message_input_index, remaining_transaction_inputs) transaction_input = remaining_transaction_inputs.shift if transaction_input.nil? start_waiting_for_completed return end if transaction_input['address'] == input_address transaction_signature_message = Coinmux::Message::TransactionSignature.build( coin_join_message, transaction_input_index: transaction_message_input_index, private_key: input_private_key) insert_message(:transaction_signatures, transaction_signature_message) do insert_transaction_signature(transaction_message_input_index + 1, remaining_transaction_inputs) end else insert_transaction_signature(transaction_message_input_index + 1, remaining_transaction_inputs) end end def start_waiting_for_completed notify(:waiting_for_completed) wait_for_state('completed') do refresh_message(:status) do transaction_id = coin_join_message.status.value.transaction_id notify(:completed, transaction_id: transaction_id, message: "Transaction ID: #{transaction_id}") end end end def wait_for_state(state, &callback) event_queue.future_exec(MESSAGE_POLL_INTERVAL) do refresh_message(:status) do if coin_join_message.status.value.try(:state) == state yield elsif coin_join_message.status.value.try(:state) == 'failed' failure(:director_failed) else wait_for_state(state, &callback) # try again end end end end # Searches for a coin_join_message in the reverse order of data added into data store. # TODO: there needs to be a better implementation to guard against flooding. # # @callback [Proc] Invoked with either a CoinJoin message or nil if none could be found. def fetch_available_coin_join_message(&callback) data_store.fetch_most_recent(data_store.coin_join_identifier, COIN_JOIN_MESSAGE_FETCH_SIZE) do |event| handle_event(event, :unable_to_search_for_most_recent_message) do coin_join_messages = event.data.collect { |json| Coinmux::Message::CoinJoin.from_json(json, data_store, nil) }.compact fetch_available_coin_join_status_message(coin_join_messages, &callback) end end end def fetch_available_coin_join_status_message(coin_join_messages, &callback) if (coin_join = coin_join_messages.pop).nil? yield(nil) # none left, so no match else if coin_join.amount == amount && coin_join.participants == participants refresh_message(:status, coin_join) do if coin_join.status.value && coin_join.status.value.state == 'waiting_for_inputs' refresh_message(:inputs, coin_join) do if coin_join.inputs.value.size < participants yield(coin_join) # found it! else fetch_available_coin_join_status_message(coin_join_messages, &callback) # try next end end else fetch_available_coin_join_status_message(coin_join_messages, &callback) # try next end end else fetch_available_coin_join_status_message(coin_join_messages, &callback) # try next end end end def failure(error_identifier, error_message = nil) notify(:failed, message: "#{error_identifier}#{": #{error_message}" if error_message}") end end
michaelgpearce/coinmux
lib/coinmux/file_util.rb
require 'fileutils' require 'tmpdir' module Coinmux::FileUtil import 'java.io.FileInputStream' import 'java.io.InputStreamReader' import 'java.io.ByteArrayOutputStream' import 'java.io.IOException' class << self def root_mkdir_p(*paths) begin FileUtils.mkdir_p(path = File.join(Coinmux.root, *paths)) rescue FileUtils.mkdir_p(path = File.join(Dir.tmpdir, *paths)) end path end def read_content(*paths) Java::JavaLang::String.new(read_content_as_java_bytes(*paths)).to_s end def read_content_as_java_bytes(*paths) begin input_stream = begin FileInputStream.new(File.join(Coinmux.root, *paths)) # file system rescue IOException => e "".to_java.java_class.resource_as_stream("/#{paths.join('/')}") # Jar file end read_java_bytes(input_stream) ensure input_stream.close() if input_stream end end private def read_java_bytes(input_stream) buffer = Java::byte[8192].new output_stream = ByteArrayOutputStream.new while (bytes_read = input_stream.read(buffer)) >= 0 output_stream.write(buffer, 0, bytes_read) end output_stream.toByteArray() end end end
michaelgpearce/coinmux
lib/coinmux/message/input.rb
class Coinmux::Message::Input < Coinmux::Message::Base property :message_public_key, :address, :change_address, :change_transaction_output_identifier, :signature attr_accessor :message_private_key, :private_key validates :message_public_key, :address, :signature, :change_transaction_output_identifier, :presence => true validate :signature_correct validate :change_address_valid, :if => :change_address validate :change_amount_not_more_than_transaction_fee_with_no_change_address, :unless => :change_address validate :input_has_enough_value class << self def build(coin_join, options = {}) options.assert_keys!(required: :private_key, optional: :change_address) message = super(coin_join.data_store, coin_join) message.message_private_key, message.message_public_key = pki_facade.generate_keypair message.private_key = options[:private_key] begin message.address = bitcoin_crypto_facade.address_for_private_key!(options[:private_key]) rescue Coinmux::Error end begin message.signature = bitcoin_crypto_facade.sign_message!(coin_join.identifier, options[:private_key]) rescue Coinmux::Error end message.change_address = options[:change_address] message.change_transaction_output_identifier = digest_facade.random_identifier message end end private def signature_correct unless bitcoin_crypto_facade.verify_message(coin_join.identifier, signature, address) errors[:signature] << "is not correct for address #{address}" end end def change_address_valid unless bitcoin_crypto_facade.verify_address(change_address) errors[:change_address] << "is not a valid address" end end def change_amount_not_more_than_transaction_fee_with_no_change_address unspent_value = coin_join.unspent_value!(address) rescue 0 if unspent_value - coin_join.amount > coin_join.participant_transaction_fee errors[:change_address] << "required for this input address" end end def input_has_enough_value unless coin_join.input_has_enough_unspent_value?(address) errors[:address] << "does not have enough unspent value" end end end
michaelgpearce/coinmux
spec/fake/bitcoin_network.rb
<filename>spec/fake/bitcoin_network.rb class Coinmux::Fake::BitcoinNetwork def initialize @blocks = [] @transaction_pool = [] test_confirm_block end # nil returned if transaction not found, 0 returned if in transaction pool, 1+ if accepted into blockchain def transaction_confirmations(transaction_id) if @transaction_pool.include?(transaction_id) 0 elsif block_index = test_find_block_index_with_transaction_id(transaction_id) block_index + 1 else nil end end def test_add_transaction_id_to_pool(transaction_id) @transaction_pool << transaction_id end def test_confirm_block @blocks << {:nonce => rand(1..1_000_000), :transaction_ids => @transaction_pool.dup} @transaction_pool.clear end private def test_find_block_index_with_transaction_id(transaction_id) @blocks.find_index { |block| block[:transaction_ids].include?(transaction_id) } end end
michaelgpearce/coinmux
spec/state_machine/director_spec.rb
<reponame>michaelgpearce/coinmux require 'spec_helper' describe Coinmux::StateMachine::Director do before do fake_all end # describe "#initialize" do # subject do # Coinmux::StateMachine::Director.new # end # it "should be in the initialized state" do # expect(subject.state).to eq('initialized') # end # end # describe "#start" do # let(:director) { Coinmux::StateMachine::Director.new } # let(:bitcoin_amount) { 100_000_000 } # let(:participant_count) { 5 } # let(:coin_join_data_store_identifier) { Coinmux::CoinJoinUri.parse(config_facade.coin_join_uri).identifier } # subject do # callback_events = [] # director.start(bitcoin_amount, participant_count) do |e| # callback_events << e # end # callback_events # end # context "with valid input" do # it "invokes callback with no error" do # callback_events = subject # expect(callback_events.collect(&:type)).to eq([:inserting_status_message, :inserting_coin_join_message, :waiting_for_inputs]) # end # it "has status waiting_for_inputs" do # subject # expect(director.state).to eq('waiting_for_inputs') # end # it "inserts coin join message" do # subject # expect(data_store.fetch(coin_join_data_store_identifier).last).to eq(director.coin_join_message.to_json) # end # it "inserts status message" do # subject # expect(data_store.fetch(director.coin_join_message.status.data_store_identifier).last).to eq(director.status_message.to_json) # expect(director.status_message.status).to eq('WaitingForInputs') # expect(director.status_message.transaction_id).to be_nil # end # end # end end
michaelgpearce/coinmux
gui/component/link_button.rb
class Gui::Component::LinkButton < Java::JavaxSwing::JButton import 'java.awt.Color' import 'java.awt.Cursor' import 'java.awt.Insets' import 'javax.swing.UIManager' def initialize(label = nil) super(label.to_s) setBorderPainted(false) setBorder(nil) setMargin(Insets.new(0, 0, 0, 0)) setCursor(Cursor.getPredefinedCursor(Cursor::HAND_CURSOR)) setOpaque(false) setContentAreaFilled(false) setForeground(Color.blue) end end
michaelgpearce/coinmux
spec/http_spec.rb
require 'spec_helper' describe Coinmux::Http do before do Coinmux::Http.instance.send(:clear_cache) end describe "#get" do let(:http) { Coinmux::Http.instance } let(:host) { 'http://valid-host.example.com' } let(:path) { '/valid/path.html' } let(:code) { '200' } let(:body) { 'some content' } let(:response) { double(code: code, body: body) } before do Net::HTTP.stub(:get_response).with(URI("#{host}#{path}")).and_return(response) end subject { http.get(host, path) } context "with 200 response code" do it "returns body" do expect(subject).to eq(body) end end context "with non-200 response code" do let(:code) { '404' } it "raises error" do expect { subject }.to raise_error(Coinmux::Error) end end context "with invocation of previously invoked url" do before do http.get(host, path) end it "return cached value" do Net::HTTP.stub(:get_response).with(URI("#{host}#{path}")).never subject end end end describe "#post" do let(:http) { Coinmux::Http.instance } let(:host) { 'http://valid-host.example.com' } let(:path) { '/valid/path.html' } let(:data) { { "random-key-#{rand}" => "some data #{rand}" } } let(:code) { '200' } let(:body) { 'some content' } let(:response) { double(code: code, body: body) } before do Net::HTTP.stub(:post_form).with(URI("#{host}#{path}"), data).and_return(response) end subject { http.post(host, path, data) } context "with 200 response code" do it "returns body" do expect(subject).to eq(body) end end context "with non-200 response code" do let(:code) { '404' } it "raises error" do expect { subject }.to raise_error(Coinmux::Error) end end end end
michaelgpearce/coinmux
lib/coinmux/proper.rb
<filename>lib/coinmux/proper.rb module Coinmux::Proper module ClassMethods def properties @properties ||= [] end def property(*names) names.each do |name| properties << name.to_sym define_method(name) do self[name] end define_method(:"#{name}=") do |value| self[name] = value end end end end module InstanceMethods def [](property) properties[property.to_s] end def []=(property, value) properties[property.to_s] = value end def properties @properties ||= {} end def to_hash properties.dup end def to_json to_hash.to_json end def ==(other) return false unless other.is_a?(self.class) return properties == other.properties end end def self.included(base) base.send(:include, InstanceMethods) base.send(:extend, ClassMethods) end end
michaelgpearce/coinmux
lib/coinmux/data_store/base.rb
class Coinmux::DataStore::Base include Coinmux::Facades DATA_TIME_TO_LIVE = 1 * 60 * 60 attr_accessor :coin_join_uri, :connected def initialize(coin_join_uri) self.connected = false self.coin_join_uri = coin_join_uri end def coin_join_identifier "#{coin_join_uri.params["identifier"] || "default"}-rw" end def connect(&callback) self.connected = true yield(Coinmux::Event.new) end def disconnect(&callback) self.connected = false yield(Coinmux::Event.new) if block_given? end def generate_identifier "#{digest_facade.random_identifier}-rw" end def convert_to_request_only_identifier(identifier) identifier.gsub(/-rw$/, '-ro') end def identifier_can_insert?(identifier) !!(identifier =~ /-rw$/) end def identifier_can_request?(identifier) true end def insert(identifier, data, &callback) raise "Cannot insert" unless identifier_can_insert?(identifier) raise "Data store not connected" unless connected key = key_from_identifier(identifier) array = read(key) || [] array << data write(key, array) debug "DATASTORE INSERT #{identifier}: #{data}" yield(Coinmux::Event.new(:data => data)) end def fetch_first(identifier, &callback) yield(Coinmux::Event.new(:data => fetch(identifier).first)) end def fetch_last(identifier, &callback) yield(Coinmux::Event.new(:data => fetch(identifier).last)) end def fetch_all(identifier, &callback) yield(Coinmux::Event.new(:data => fetch(identifier))) end # items are in reverse inserted order def fetch_most_recent(identifier, max_items, &callback) data = fetch(identifier) yield(Coinmux::Event.new(:data => (data[-1*max_items..-1] || data).reverse)) end private def key_from_identifier(identifier) identifier.gsub(/-r.$/, '') end def fetch(identifier) raise "Data store not connected" unless connected key = key_from_identifier(identifier) data = (read(key) || []).clone debug "DATASTORE FETCH #{identifier}: #{data}" data end end
michaelgpearce/coinmux
spec/fake/application.rb
<reponame>michaelgpearce/coinmux<gh_stars>10-100 class Coinmux::Fake::Application class Invocation include Coinmux::Proper property :block, :time, :seconds def <=>(other) self.time <=> other.time end end attr_reader :invocations def initialize @invocations = [] @current_time = 0 end def invoke(&block) yield while next_invocation invocation.block.call end end def sync_exec(&block) yield end def future_exec(seconds = 0, &block) add_invocation(seconds, block) end private def next_invocation invocation = invocations.shift @current_time = invocation.time invocation end def add_invocation(seconds, block) invocation = Invocation.new(:seconds => seconds, :time => @current_time + seconds, :block => block) invocations << invocation invocations.sort! invocation end end
michaelgpearce/coinmux
bin/coinmux_cli.rb
raise "COINMUX_ENV not set" if ENV['COINMUX_ENV'].nil? require File.expand_path("../../lib/coinmux", __FILE__) module Cli end require 'optparse' require 'ostruct' options = OpenStruct.new OptionParser.new do |o| o.banner = "#{Coinmux::BANNER}\n\nUsage: coinmux [options]\n" o.separator "" o.on('-v', '--version', 'Display the version') { |v| options.version = v } o.on('-h', '--help', 'Display this help message') { |v| options.help = v } o.on('-l', '--list', 'List CoinJoins waiting for inputs') { |v| options.list = v } o.on('-a', '--amount AMOUNT', 'CoinJoin transaction amount (in BTC)') { |v| options.amount = v } o.on('-p', '--participants PARTICIPANTS', 'Number of participants') { |v| options.participants = v } o.on('-o', '--output-address OUTPUTADDRESS', 'Output address (in BTC)') { |v| options.output_address = v } o.on('-c', '--change-address [CHANGEADDRESS]', 'Change address (in BTC)') { |v| options.change_address = v } o.on('-k', '--private-key [PRIVATEKEY]', 'Input private key in hex or wallet import format *NOT SECURE*') { |v| options.private_key = v } o.on('-d', '--data-store DATASTORE', 'Data store to use: p2p <default> or filesystem') { |v| options.data_store = v } o.on('-b', '--bootstrap [PORT]', 'Run as P2P bootstrap server') { |v| options.bootstrap = v } end.parse! if options.version puts Coinmux::VERSION elsif options.bootstrap require 'cli/bootstrap' Cli::Bootstrap.new(port: options.bootstrap).startup else require 'cli/event' require 'cli/event_queue' require 'cli/application' app = Cli::Application.new( amount: options.amount, participants: options.participants, input_private_key: options.private_key, output_address: options.output_address, change_address: options.change_address, data_store: options.data_store, list: options.list ) if options.list app.list_coin_joins else app.start end end
michaelgpearce/coinmux
gui/view/mixing.rb
<filename>gui/view/mixing.rb class Gui::View::Mixing < Gui::View::Base STATES = [:initializing, :waiting_for_other_inputs, :waiting_for_other_outputs, :waiting_for_completed, :completed] TERMINATE_TEXT = "Terminate" attr_accessor :director, :participant, :transaction_url, :mixer import 'java.awt.Component' import 'java.awt.Dimension' import 'java.awt.GridLayout' import 'javax.swing.BorderFactory' import 'javax.swing.JButton' import 'javax.swing.JOptionPane' import 'javax.swing.JPanel' import 'javax.swing.JProgressBar' protected def handle_add add_header("Mixing") add_row do |parent| container = JPanel.new(GridLayout.new(0, 1, 0, 10)).tap do |container| container.setBorder(BorderFactory.createEmptyBorder(0, 40, 0, 40)) container.add(status_label) container.add(progress_bar) JPanel.new.tap do |panel| panel.add(show_transaction_button) container.add(panel) end end parent.add(container, build_grid_bag_constraints(fill: :horizontal, anchor: :center)) end add_button_row(action_button) end def handle_show transaction_url = nil show_transaction_button.setVisible(false) reset_status action_button.setLabel(TERMINATE_TEXT) (self.mixer = build_mixer).start do |event| if event.source == :participant && STATES.include?(event.type) Gui::EventQueue.instance.sync_exec do update_status(event.type, event.options) if event.type == :completed handle_success(event.options[:transaction_id]) elsif event.type == :failed handle_failure end end end end end private def build_mixer Coinmux::Application::Mixer.new( event_queue: Gui::EventQueue.instance, data_store: application.data_store, amount: application.amount, participants: application.participants, input_private_key: application.input_private_key, output_address: application.output_address, change_address: application.change_address) end def handle_success(transaction_id) progress_bar.setValue(progress_bar.getMaximum()) action_button.setLabel("Done") self.transaction_url = Coinmux::Config.instance.show_transaction_url % transaction_id show_transaction_button.setVisible(true) end def handle_failure progress_bar.setValue(progress_bar.getMaximum()) end def reset_status update_status(:initializing) end def update_status(state, options = {}) index = STATES.index(state) progress_bar.setValue(index) status_label.setText(state.to_s.capitalize.gsub(/_/, ' ')) end def status_label @status_label ||= JLabel.new("", JLabel::CENTER).tap do |label| font = label.getFont() label.setFont(Font.new(font.getName(), Font::PLAIN, (font.getSize() * 1.6).to_i)) end end def show_transaction_button @show_transaction_button ||= Gui::Component::LinkButton.new("View transaction").tap do |button| button.addActionListener do |e| application.open_webpage(transaction_url) end end end def progress_bar @progress_bar ||= JProgressBar.new.tap do |progress_bar| progress_bar.setMinimum(0) progress_bar.setMaximum(STATES.size - 1) end end def action_button @action_button ||= JButton.new(TERMINATE_TEXT).tap do |action_button| action_button.addActionListener() do |e| if action_button.getLabel() == TERMINATE_TEXT result = JOptionPane.showConfirmDialog(application.root_panel, "Are you sure you want to terminate this mix?", "Coinmux", JOptionPane::YES_NO_OPTION, JOptionPane::WARNING_MESSAGE) if result == JOptionPane::YES_OPTION application.show_view(:available_mixes) # TODO: clean_up_coin_join end else application.show_view(:available_mixes) end end end end end
michaelgpearce/coinmux
cli/event_queue.rb
<reponame>michaelgpearce/coinmux require 'thread' require 'set' class Cli::EventQueue include Singleton, Coinmux::BitcoinUtil attr_reader :queue, :event_thread def initialize @queue = Queue.new end def start @event_thread = start_event_thread nil end def stop # nil message in queue kills event thread queue << nil nil end def wait event_thread.join end def sync_exec(&callback) if Thread.current == event_thread yield else mutex = Mutex.new condition_variable = ConditionVariable.new mutex.synchronize do queue << Cli::Event.new( mutex: mutex, condition_variable: condition_variable, callback: callback) condition_variable.wait(mutex) end end end def future_exec(seconds = 0, &callback) queue << Cli::Event.new( invoke_at: Time.now + seconds, callback: callback) nil end private def start_event_thread Thread.new do while event = queue.pop # nil in the event thread indicates to quit events_to_enqueue = [] all_events = [event] + queue.size.times.collect { queue.pop } all_events.each do |event| if event.nil? # nil in the event thread indicates to quit break elsif event.invoke_at && Time.now < event.invoke_at # interval has not passed, so re-enqueue events_to_enqueue << event else # invoke the callback invocation = lambda do begin event.callback.call rescue puts "Unhandled exception in event thread: #{$!}" puts $!.backtrace end end if event.mutex event.mutex.synchronize do begin invocation.call ensure event.condition_variable.signal end end else invocation.call end end end if !events_to_enqueue.empty? sleep(0.1) # so we don't use all the CPU, let's sleep a little before we continue our event thread events_to_enqueue.each { |e| queue << e } end end end end end
michaelgpearce/coinmux
lib/coinmux/facades.rb
<gh_stars>10-100 module Coinmux::Facades module Methods def bitcoin_crypto_facade Coinmux::BitcoinCrypto.instance end def bitcoin_network_facade Coinmux::BitcoinNetwork.instance end def cipher_facade Coinmux::Cipher.instance end def config_facade Coinmux::Config.instance end def digest_facade Coinmux::Digest.instance end def http_facade Coinmux::Http.instance end def pki_facade Coinmux::PKI.instance end def debug(*messages) Coinmux::Logger.instance.debug(*messages) end def info(*messages) Coinmux::Logger.instance.info(*messages) end def warn(*messages) Coinmux::Logger.instance.warn(*messages) end def error(*messages) Coinmux::Logger.instance.error(*messages) end def fatal(*messages) Coinmux::Logger.instance.fatal(*messages) end end def self.included(base) base.extend(Methods) base.send(:include, Methods) end end
nkipreos/Post-Tester
app/models/request.rb
class Request < ActiveRecord::Base belongs_to :page end
koki1023/apnotic
lib/apnotic/abstract_notification.rb
# frozen_string_literal: true require 'securerandom' require 'json' module Apnotic class AbstractNotification attr_reader :token attr_accessor :apns_id, :expiration, :priority, :topic, :apns_collapse_id, :authorization :rpr_attachment def initialize(token) @token = token @apns_id = SecureRandom.uuid end def body JSON.dump(to_hash).force_encoding(Encoding::BINARY) end def authorization_header authorization ? "bearer #{authorization}" : nil end def background_notification? false end private def to_hash raise NotImplementedError, 'implement the to_hash method in a child class' end end end
TxbitExchange/coingecko-cryptoexchange
lib/cryptoexchange/exchanges/zgtop/market.rb
<gh_stars>1-10 module Cryptoexchange::Exchanges module Zgtop class Market < Cryptoexchange::Models::Market NAME = 'zgtop' API_URL = 'https://www.zg.top/API/api/v2' def self.trade_page_url(args={}) "https://www.zg.top" end end end end
TxbitExchange/coingecko-cryptoexchange
lib/cryptoexchange/exchanges/uniswap/market.rb
module Cryptoexchange::Exchanges module Uniswap class Market < Cryptoexchange::Models::Market NAME = 'uniswap' API_URL = 'https://uniswap-analytics.appspot.com/api/v1' end end end
TxbitExchange/coingecko-cryptoexchange
spec/exchanges/txbit/integration/market_spec.rb
require 'spec_helper' RSpec.describe 'Txbit integration specs' do let(:client) { Cryptoexchange::Client.new } let(:market) { 'txbit' } let(:btc_atl_pair) { Cryptoexchange::Models::MarketPair.new(base: 'atl', target: 'btc', market: 'txbit') } it 'fetch pairs' do pairs = client.pairs('txbit') expect(pairs).not_to be_empty pair = pairs.first expect(pair.base).to_not be nil expect(pair.target).to_not be nil expect(pair.market).to eq 'txbit' end it 'give trade url' do trade_page_url = client.trade_page_url market, target: btc_atl_pair.target, base: btc_atl_pair.base expect(trade_page_url).to eq "https://txbit.io/Trade/ATL/BTC" end it 'fetch pairs and assign the correct base/target' do pairs = client.pairs('txbit') expect(pairs).not_to be_empty pair = pairs.first expect(pair.base).to eq 'ATL' expect(pair.target).to eq 'BTC' expect(pair.market).to eq 'txbit' end it 'fetch ticker' do ticker = client.ticker(btc_atl_pair) expect(ticker.base).to eq 'ATL' expect(ticker.target).to eq 'BTC' expect(ticker.market).to eq 'txbit' expect(ticker.ask).to be_a Numeric expect(ticker.bid).to be_a Numeric expect(ticker.last).to be_a Numeric expect(ticker.high).to be_a Numeric expect(ticker.low).to be_a Numeric expect(ticker.volume).to be_a Numeric expect(ticker.timestamp).to be_a Numeric expect(2000..Date.today.year).to include(Time.at(ticker.timestamp).year) expect(ticker.payload).to_not be nil end it 'fail to parse ticker' do expect { client.ticker(Cryptoexchange::Models::MarketPair.new(base: 'btc', target: 'xxxxx', market: 'txbit')) }.to raise_error(Cryptoexchange::ResultParseError) end end
TxbitExchange/coingecko-cryptoexchange
lib/cryptoexchange/client.rb
<reponame>TxbitExchange/coingecko-cryptoexchange<gh_stars>1-10 module Cryptoexchange class Client def initialize(ticker_ttl: 3, cache_size: 200) LruTtlCache.ticker_cache(ticker_ttl, cache_size) end def trade_page_url(exchange, args={}) pairs_classname = "Cryptoexchange::Exchanges::#{StringHelper.camelize(exchange)}::Market" pairs_class = Object.const_get(pairs_classname) pairs_class.trade_page_url(base: args[:base], target: args[:target]) end def pairs(exchange) pairs_classname = "Cryptoexchange::Exchanges::#{StringHelper.camelize(exchange)}::Services::Pairs" pairs_class = Object.const_get(pairs_classname) pairs_object = pairs_class.new pairs_object.fetch rescue HttpResponseError, HttpConnectionError, HttpTimeoutError, HttpBadRequestError, JsonParseError, JSON::ParserError, TypeFormatError, CredentialsMissingError, OpenSSL::SSL::SSLError, HTTP::Redirector::EndlessRedirectError => e # temporary or permanent failure, omit return {error: [e]} end def ticker(market_pair) exchange = market_pair.market market_classname = "Cryptoexchange::Exchanges::#{StringHelper.camelize(exchange)}::Services::Market" market_class = Object.const_get(market_classname) market = market_class.new if market_class.supports_individual_ticker_query? market.fetch(market_pair) else tickers = market.fetch tickers.find do |t| t.base.casecmp(market_pair.base) == 0 && t.target.casecmp(market_pair.target) == 0 end end end def available_exchanges folder_names = Dir[File.join(File.dirname(__dir__), 'cryptoexchange', 'exchanges', '**')] folder_names.map do |folder_name| folder_name.split('/').last end.sort end def exchange_for(currency) exchanges = [] available_exchanges.each do |exchange| pairs = pairs(exchange) next if pairs.is_a?(Hash) && !pairs[:error].empty? pairs.compact.each do |pair| if [pair.base, pair.target].include?(currency.upcase) exchanges << exchange break end end end exchanges.uniq.sort end def order_book(market_pair) exchange = market_pair.market market_classname = "Cryptoexchange::Exchanges::#{StringHelper.camelize(exchange)}::Services::OrderBook" market_class = Object.const_get(market_classname) order_book = market_class.new if market_class.supports_individual_ticker_query? order_book.fetch(market_pair) else order_books = order_book.fetch order_books.find do |o| o.base.casecmp(market_pair.base) == 0 && o.target.casecmp(market_pair.target) == 0 end end end def trades(market_pair) exchange = market_pair.market market_classname = "Cryptoexchange::Exchanges::#{StringHelper.camelize(exchange)}::Services::Trades" market_class = Object.const_get(market_classname) trades = market_class.new trades.fetch(market_pair) end def ticker_stream(market_pair:, onopen: nil, onmessage:, onclose: nil) fetch_stream( market_pair: market_pair, onopen: onopen, onmessage: onmessage, onclose: onclose, stream_type: 'market' ) end def trade_stream(market_pair:, onopen: nil, onmessage:, onclose: nil) fetch_stream( market_pair: market_pair, onopen: onopen, onmessage: onmessage, onclose: onclose, stream_type: 'trade' ) end def order_book_stream(market_pair:, onopen: nil, onmessage:, onclose: nil) fetch_stream( market_pair: market_pair, onopen: onopen, onmessage: onmessage, onclose: onclose, stream_type: 'order_book' ) end private # NOTE: # https://ruby-doc.org/core-2.5.0/Thread.html#method-c-abort_on_exception # When set to true, if any thread is aborted by an exception, the raised exception will be re-raised in the main thread. def fetch_stream(market_pair:, onopen: nil, onmessage:, onclose: nil, stream_type:) fail 'stream_type must be one of "market", "trade", "order_book"' unless %w(market trade order_book).include?(stream_type) exchange = market_pair.market stream_classname = "Cryptoexchange::Exchanges::#{StringHelper.camelize(exchange)}::Services::#{StringHelper.camelize(stream_type)}Stream" stream_class = Object.const_get(stream_classname) stream = stream_class.new Thread.new do EM.run do ws = WebSocket::EventMachine::Client.connect(uri: stream.url) ws.onopen do onopen.call if onopen ws.send(stream.subscribe_event(market_pair)) end ws.onmessage do |message, _| message = JSON.parse(message) if stream.valid_message?(message) onmessage.call(stream.parse_message(message, market_pair)) end end ws.onclose do onclose.call if onclose end end end end end end
TxbitExchange/coingecko-cryptoexchange
lib/cryptoexchange/exchanges/trx_market/market.rb
module Cryptoexchange::Exchanges module TrxMarket class Market < Cryptoexchange::Models::Market NAME = 'trx_market' API_URL = 'https://trx.market' def self.trade_page_url(args={}) "https://trx.market/exchange" end end end end
TxbitExchange/coingecko-cryptoexchange
lib/cryptoexchange/exchanges/uniswap/services/market.rb
<reponame>TxbitExchange/coingecko-cryptoexchange<filename>lib/cryptoexchange/exchanges/uniswap/services/market.rb module Cryptoexchange::Exchanges module Uniswap module Services class Market < Cryptoexchange::Services::Market class << self def supports_individual_ticker_query? true end end def fetch(market_pair) output = super(ticker_url(market_pair)) adapt(output, market_pair) end def ticker_url(market_pair) pairs = Cryptoexchange::Exchanges::Uniswap::Services::Pairs.new.fetch pair = pairs.select { |s| s.base == market_pair.base }.first exchangeAddress = pair.inst_id "#{Cryptoexchange::Exchanges::Uniswap::Market::API_URL}/ticker?exchangeAddress=#{exchangeAddress}" end def adapt(output, market_pair) ticker = Cryptoexchange::Models::Ticker.new ticker.base = market_pair.base ticker.target = market_pair.target ticker.market = Uniswap::Market::NAME ticker.last = NumericHelper.divide(1, NumericHelper.to_d(output['lastTradePrice'])) ticker.high = NumericHelper.divide(1, NumericHelper.to_d(output['highPrice'])) ticker.low = NumericHelper.divide(1, NumericHelper.to_d(output['lowPrice'])) ticker.volume = (NumericHelper.to_d(output['tradeVolume']) / 10**18) / ticker.last ticker.timestamp = nil ticker.payload = output ticker end end end end end
rrreeeyyy/promrule
lib/promrule/version.rb
<filename>lib/promrule/version.rb module Promrule VERSION = "0.1.0" end
rrreeeyyy/promrule
lib/promrule.rb
require "promrule/version"
rrreeeyyy/promrule
spec/promrule_spec.rb
require "spec_helper" RSpec.describe Promrule do it "has a version number" do expect(Promrule::VERSION).not_to be nil end it "does something useful" do expect(false).to eq(true) end end __END__ group do record "instance:errors:rate5m" do expr "rate(errors_total[5m])" end record "instance:requests:rate5m" do expr "rate(request_total[5m])" end alert "HighErrors" do expr( <<-"EOE" sum without(instance) (instance:errors:rate5m) / sum without(instance) (instance:requests:rate5m) EOE ) for "5m" labels do severity "critical" end annotations do description: "stuff's happening with {{ $labels.service }}" end end end
kingdonb/kuby-cert-manager
lib/kuby/cert-manager.rb
require 'kuby/cert-manager/plugin' module Kuby module CertManager autoload :AcmeStrategy, 'kuby/cert-manager/acme_strategy' autoload :ClusterIssuer, 'kuby/cert-manager/cluster_issuer' autoload :ClusterIssuerSpec, 'kuby/cert-manager/cluster_issuer_spec' autoload :Http01Solver, 'kuby/cert-manager/http01_solver' autoload :Http01SolverIngress, 'kuby/cert-manager/http01_solver_ingress' autoload :PrivateKeySecretRef, 'kuby/cert-manager/private_key_secret_ref' autoload :Solver, 'kuby/cert-manager/solver' end end Kuby.register_plugin(:cert_manager, Kuby::CertManager::Plugin)
kingdonb/kuby-cert-manager
lib/kuby/cert-manager/plugin.rb
<filename>lib/kuby/cert-manager/plugin.rb require 'kuby' module Kuby module CertManager class Plugin < ::Kuby::Plugin class Config extend ::KubeDSL::ValueFields value_fields :email end NAMESPACE = 'cert-manager'.freeze CERT_MANAGER_VERSION = '1.6.1'.freeze CERT_MANAGER_RESOURCE = "https://github.com/jetstack/cert-manager/releases/download/v#{CERT_MANAGER_VERSION}/cert-manager.yaml".freeze def configure(&block) @config.instance_eval(&block) if block end def setup install_cert_manager end def resources @resources ||= [cluster_issuer] end def annotate_ingress(ingress) context = self ingress.metadata do annotations do add :'cert-manager.io/cluster-issuer', context.send(:issuer_name) end end end private def issuer_name @issuer_name ||= "letsencrypt-#{environment.name}" end # hard-code this stuff for now def cluster_issuer context = self config = @config @cluster_issuer ||= ClusterIssuer.new do metadata do name context.send(:issuer_name) namespace NAMESPACE end spec do acme do server 'https://acme-v02.api.letsencrypt.org/directory' email config.email private_key_secret_ref do name context.send(:issuer_name) end solver do http01 do ingress do ingress_class 'nginx' end end end end end end end def install_cert_manager Kuby.logger.info('Installing cert-manager...') kubernetes_cli.apply_uri(CERT_MANAGER_RESOURCE) Kuby.logger.info('cert-manager installed successfully!') rescue => e Kuby.logger.fatal(e.message) raise end def after_initialize @config = Config.new end def spec environment.kubernetes end def kubernetes_cli spec.provider.kubernetes_cli end end end end
kingdonb/kuby-cert-manager
lib/kuby/cert-manager/http01_solver.rb
<filename>lib/kuby/cert-manager/http01_solver.rb module Kuby module CertManager class Http01Solver < ::KubeDSL::DSLObject object_field(:ingress) { Http01SolverIngress.new } def serialize {}.tap do |result| result[:ingress] = ingress.serialize end end def kind_sym :http01_solver end end end end
kingdonb/kuby-cert-manager
lib/kuby/cert-manager/solver.rb
<gh_stars>0 module Kuby module CertManager class Solver < ::KubeDSL::DSLObject object_field(:http01) { Http01Solver.new } def serialize {}.tap do |result| result[:http01] = http01.serialize end end def kind_sym :http01 end end end end
kingdonb/kuby-cert-manager
lib/kuby/cert-manager/acme_strategy.rb
module Kuby module CertManager class AcmeStrategy < ::KubeDSL::DSLObject value_fields :server, :email object_field(:private_key_secret_ref) { PrivateKeySecretRef.new } array_field(:solver) { Solver.new } def serialize {}.tap do |result| result[:server] = server result[:email] = email result[:privateKeySecretRef] = private_key_secret_ref.serialize result[:solvers] = solvers.map(&:serialize) end end def kind_sym :acme_strategy end end end end
kingdonb/kuby-cert-manager
lib/kuby/cert-manager/cluster_issuer_spec.rb
<filename>lib/kuby/cert-manager/cluster_issuer_spec.rb module Kuby module CertManager class ClusterIssuerSpec < ::KubeDSL::DSLObject object_field(:acme) { AcmeStrategy.new } def serialize {}.tap do |result| result[:acme] = acme.serialize end end def to_resource ::KubeDSL::Resource.new(serialize) end def kind_sym :cluster_issuer_spec end end end end
kingdonb/kuby-cert-manager
lib/kuby/cert-manager/http01_solver_ingress.rb
module Kuby module CertManager class Http01SolverIngress < ::KubeDSL::DSLObject value_fields :ingress_class def serialize {}.tap do |result| result[:class] = ingress_class end end def kind_sym :http01_solver_ingress end end end end
kingdonb/kuby-cert-manager
lib/kuby/cert-manager/private_key_secret_ref.rb
<gh_stars>0 module Kuby module CertManager class PrivateKeySecretRef < ::KubeDSL::DSLObject value_fields :name def serialize {}.tap do |result| result[:name] = name end end def kind_sym :private_key_secret_ref end end end end
alpinelab/codestyle
alpinelab-codestyle.gemspec
# frozen_string_literal: true lib = File.expand_path("lib", __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "alpine_lab/code_style/version" Gem::Specification.new do |spec| spec.name = "alpinelab-codestyle" spec.version = AlpineLab::CodeStyle::VERSION spec.files = Dir["README.md", "LICENSE.md", "config/*.yml"] spec.summary = "Code style used by AlpineLab" spec.description = <<~DESCRIPTION This repository holds linter rules (e.g. Rubocop) that enforce our code style in any project (thanks to Rubocop `inherit_gem' directive) as well as other conventions not transposable as automated rules (those are explained as plain Markdown). DESCRIPTION spec.license = "MIT" spec.homepage = "https://www.alpine-lab.com" spec.authors = ["AlpineLab developers"] spec.email = ["<EMAIL>"] spec.required_ruby_version = ">= 2.3.0" spec.add_development_dependency "bundler" spec.add_development_dependency "rake" end
alpinelab/codestyle
lib/alpine_lab/code_style/version.rb
<gh_stars>1-10 # frozen_string_literal: true module AlpineLab module CodeStyle VERSION = "0.8.0" end end
iCentris/time_zone_ext
lib/time_zone_ext.rb
require 'tzinfo' require "active_support/core_ext" require "time_zone_ext/version" require "date" require "i18n" module TimeZoneExt def strptime(date, format, locale: I18n.locale) locale ||= I18n.config.locale if format =~ /%z/i DateTime.strptime(unlocalize_date_string(date,locale), format).in_time_zone else time_in_zone = DateTime.strptime(unlocalize_date_string("#{date} zone#{formatted_offset}",locale), "#{format} zone%z").in_time_zone if time_in_zone.formatted_offset != formatted_offset DateTime.strptime(unlocalize_date_string("#{date} zone#{time_in_zone.formatted_offset}",locale), "#{format} zone%z").in_time_zone else time_in_zone end end end # This method converts preffered language month names to # English month names based on the locale passed . # https://github.com/karnov/i18n-date def unlocalize_date_string(string, locale = nil) locale ||= I18n.config.locale I18n.enforce_available_locales!(locale) CONVERTIONS.reduce(string) do |s, (type, replacements)| tmp_array = Array.new date_map = {} map = I18n.t(type, scope: "date", locale: locale) map.each { |r| tmp_array.push(r.to_s.gsub('.','')) } map = tmp_array.zip(replacements).to_h.tap { |h| h.delete("") } map.collect do |k , v| if s.sub("zone", "").include?(k) date_map.merge!({s.split(' ', 2).first => v}) else date_map.merge!({k => v}) end end unloc_date_s = s.gsub(/\b(#{date_map.keys.join("|") })\b/) {|match| date_map[match] } unloc_date_s || s end end CONVERTIONS = { month_names: ::Date::MONTHNAMES, abbr_month_names: ::Date::ABBR_MONTHNAMES, day_names: ::Date::DAYNAMES, abbr_day_names: ::Date::ABBR_DAYNAMES } end ActiveSupport::TimeZone.send :include, TimeZoneExt
aquariumbio/rna-extraction-kits
libraries/MagMAXViralIINAIsolationKit.rb
# frozen_string_literal: true # Written By <NAME> 2020-05-18 needs 'Standard Libs/LabwareNames' # MagMAX Viral/Pathogen II Nucleic Acid Isolation Kit # 1) Suspend magnetic beads in buffer # 2) Proteinase K digestion # 3) Wash beads (3x) # 4) Release RNA from beads module MagMAXViralIINAIsolationKit include Units include LabwareNames NAME = 'MagMAX Viral/Pathogen II Nucleic Acid Isolation Kit' OVERAGE = 1.1 # additional 10% PLATE_SIZE = 96 SPEED = 1050 # RPM TEMP = 65 # celcius TIME1 = 1 # 1 min TIME2 = 2 # 2 min TIME3 = 3 # 3 min TIME5 = 5 # 5 min TIME10 = 10 # 10 min VOL_BEADS_PER_WELL = 10.0 VOL_BS_PER_WELL = 265.0 VOL_CONICAL_TUBE_ML = 15 VOL_ELUTION = { qty: 50, units: MICROLITERS }.freeze VOL_ETHANOL = { qty: 250, units: MICROLITERS }.freeze VOL_MS2 = { qty: 5, units: MICROLITERS }.freeze VOL_PROTEINASE_K = { qty: 5, units: MICROLITERS }.freeze VOL_SAMPLE = { qty: 200, units: MICROLITERS }.freeze VOL_WB = { qty: 500, units: MICROLITERS }.freeze # wash buffer # 265uL(buffer) + 10uL(beads)=275uL per well # Include 10% overage when making the Binding Bead Mix # for use with multiple reactions def prepare_materials total_beads = ((PLATE_SIZE * VOL_BEADS_PER_WELL * OVERAGE) / 1000).round(2) total_bs = ((PLATE_SIZE * VOL_BS_PER_WELL * OVERAGE) / 1000).round(2) total_vol = total_beads + total_bs num_tubes = { qty: (total_vol / VOL_CONICAL_TUBE_ML).round, units: TUBE_15_ML_CONICAL } bs_per_tube = { qty: total_bs / num_tubes[:qty], units: MILLILITERS } beads_per_tube = { qty: total_beads / num_tubes[:qty], units: MILLILITERS } show do title 'Prepare Binding Bead Mix' check "Vortex the Total Nucleic Acid Magnetic Beads to ensure \ that the bead mixture is homogeneous" check "Add #{qty_display(bs_per_tube)} Binding Solution per tube to \ #{qty_display(num_tubes)}" check "Add #{qty_display(beads_per_tube)} Nucleic Acid Magnetic Beads \ per tube to #{qty_display(num_tubes)}" check 'Mix well by inversion, leave at room temperature' end end def notes_on_handling; end def lyse_samples_constant_volume(sample_volume:, expert:) make_sample_plate(sample_volume: sample_volume) add_reagents_and_beads shake(time: TIME2, covered: true) incubate(time: TIME5) shake(time: TIME5, covered: true) collect_beads(time: TIME10) end def make_sample_plate(sample_volume: nil) sample_volume ||= VOL_SAMPLE operations.each do |op| input_plate = op.input('Specimen') show do title 'Add Samples to New Plate' check "Make a 96 deepwell plate according to the following table using \ #{qty_display(sample_volume)} of sample" check "Add #{qty_display(sample_volume)} of water to the wells marked \ by X as negative controls" check 'Mark the Negative Control well on the plate' title 'New Plate' table input_plate.collection.matrix end end end def add_reagents_and_beads show do title 'Add Reagents and Beads' check "Add #{qty_display(VOL_PROTEINASE_K)} of Proteinase K to each \ well of deepwell 96 Plate" check "Invert the Binding Bead Mix 5 times gently to mix, then add \ #{qty_display(VOL_PROTEINASE_K)} to each sample well and \ Negative Control well" warning "Remix the Binding Bead Mix by inversion frequently during \ pipetting to ensure even distribution of beads to all wells." warning "The Binding Bead Mix is viscous, so pipet slowly to ensure \ that the correct amount is added" check "Add #{qty_display(VOL_MS2)} of MS2 Phage Control to each sample \ well and to the Negative Control well." check 'Seal the plate with clear adhesive film' end end def shake(time:, covered:) cover = covered ? 'covered' : 'uncovered' show do title 'Shake Plate' check "Shake the <b>#{cover}</b> plate at #{SPEED} RPM for \ #{time} #{MINUTES}" timer initial: { minutes: time } end end def incubate(time:) show do title 'Incubate Sealed Plate' note 'Ensure the bottom of the plate is uncovered' check "Incubate plate at #{TEMP} #{DEGREES_C}for #{time} #{MINUTES}" timer initial: { minutes: time } end end def collect_beads(time:) show do title 'Collect Beads on Magnetic Stand' check "Place the sealed plate on the magnetic stand for \ #{time} #{MINUTES} or until all of the beads have collected" end end def bind_rna(operations:, sample_volume:, expert:); end def wash_rna(operations:, expert:) wash_beads(reagent: 'Wash Buffer', vol: VOL_WB[:qty]) wash_beads(reagent: '80% Ethanol', vol: VOL_WB[:qty]) # same as wash buffer wash_beads(reagent: '80% Ethanol', vol: VOL_ETHANOL[:qty]) shake(time: TIME2, covered: false) # dry beads end def wash_beads(reagent:, vol:) discard_supernant if reagent == 'Wash Buffer' wash(reagent: reagent, vol: vol) shake(time: TIME1, covered: true) collect_beads(time: TIME2) discard_supernant end def discard_supernant show do title 'Discard supernant' warning 'IMPORTANT! Avoid disturbing the beads' check "Keeping the plate on the magnet, carefully remove the cover, \ then discard the supernatant from each well" end end def wash(reagent:, vol:) show do title 'Wash Beads' check "Remove the plate from the magnetic stand, then add \ #{vol} #{MICROLITERS} of #{reagent} to each sample" end end def elute_rna(operations:, expert:) add_elution_solution shake(time: TIME5, covered: true) incubate(time: TIME10) shake(time: TIME5, covered: true) collect_beads(time: TIME3) make_qpcr_plate(ops: operations) end def add_elution_solution show do title 'Add Elution Solution' check "Remove the plate from the magnetic stand, then add \ #{qty_display(VOL_ELUTION)} of Elution Solution to each sample" check 'Seal the plate with Clear Adhesive Film' end end def make_qpcr_plate(ops:) ops.make ops.each do |op| input_collection = op.input('Specimen').collection input_collection.mark_as_deleted output_collection = op.output('Specimen').collection output_collection.associate_matrix(input_collection.matrix) end show do title 'Make qPCR Plate' warning "Pay special attention to transfer liquid solution only. \ Significant bead carry over may adversely impact qPCR performance" check 'Keeping the plate on the magnet, carefully remove the seal' check 'Transfer the eluates to a 96 well qPCR plate' check 'Mark the Negative Control well on the plate' check 'Seal the new plate with Clear Adhesive Film' check 'Place the plate on ice for immediate use in qPCR' end end end
aquariumbio/rna-extraction-kits
rna_extraction_kits/libraries/qiagenrneasyminikit/source.rb
<filename>rna_extraction_kits/libraries/qiagenrneasyminikit/source.rb # frozen_string_literal: true needs 'RNA Extraction Kits/QiagenRNAExtractionHelper' # Module for Qiagen RNeasy Mini Kit # # @author <NAME> <<EMAIL>> # @note The instructions here are based on the BU Center for Regenerative # Medicine COVID-19 test (http://www.bu.edu/dbin/stemcells/covid-19.php) module QiagenRNeasyMiniKit include QiagenRNAExtractionHelper NAME = 'Qiagen RNeasy Mini Kit' COLUMN_LONG = 'RNeasy spin column' MIN_SAMPLE_VOLUME = { qty: 300, units: MICROLITERS }.freeze DEFAULT_SAMPLE_VOLUME = MIN_SAMPLE_VOLUME CENTRIFUGE_SPEED = { qty: 8000, units: TIMES_G }.freeze CENTRIFUGE_TIME = { qty: 15, units: SECONDS }.freeze CENTRIFUGE_TIME_AND_SPEED = "#{Units.qty_display(CENTRIFUGE_TIME)} at " \ "#{Units.qty_display(CENTRIFUGE_SPEED)}" LYSIS_BUFFER = 'Buffer RLT' ELUTION_VOLUME = { qty: 50, units: MICROLITERS }.freeze ELUTION_TUBE_LONG = "new 1.5 #{MILLILITERS} collection tube (supplied)" ELUTION_TUBE_SHORT = 'collection tube' # @todo may need to add something from the Qiagen manual def prepare_materials; end def notes_on_handling qiagen_notes_on_handling end # @note adapted from `QIAampDSPViralRNAMiniKit` # @todo determine how much of the detail to keep or change def lyse_samples_constant_volume(sample_volume: DEFAULT_SAMPLE_VOLUME, expert: false) # TODO: Move this logic up to the calling method if sample_volume[:qty] < MIN_SAMPLE_VOLUME[:qty] msg = "Sample volume must be > #{qty_display(MIN_SAMPLE_VOLUME)}" raise ProtocolError, msg end buffer_volume = lysis_buffer_volume(sample_volume: sample_volume) ethanol_volume = ethanol_volume(sample_volume: sample_volume) show do title 'Lyse Samples' note "Get one #{LYSIS_TUBE_LONG} for each sample, and copy the IDs " \ "from the samples to the #{LYSIS_TUBE_SHORT}s." note "Pipet #{qty_display(buffer_volume)} of #{LYSIS_BUFFER} " \ "into each #{LYSIS_TUBE_SHORT}." note "Transfer #{qty_display(sample_volume)} of each sample to the " \ "corresponding #{LYSIS_TUBE_SHORT}." note "Mix by pulse-vortexing each tube for 15 #{SECONDS}." # TODO: Should this be kept in? warning 'To ensure efficient lysis, it is essential that the sample is ' \ "mixed thoroughly with #{LYSIS_BUFFER} to yield a homogeneous solution" # Frozen samples that have only been thawed once can also be used. # TODO: Should this be kept in? note "Incubate at room temperature (15-25#{DEGREES_C}) for 10 #{MINUTES}" end show do title 'Add Ethanol' note "Briefly centrifuge the #{LYSIS_TUBE_LONG}s to remove drops from " \ 'the inside of the lids.' # TODO: provision ethanol at beginning and use shorter name note "Add #{qty_display(ethanol_volume)} ethanol (100%) to each " \ 'sample, and mix by pulse-vortexing for >15 seconds. ' \ 'After mixing, briefly centrifuge the tubes to remove drops from ' \ 'inside the lids.' # Only ethanol should be used since other alcohols may result in # reduced RNA yield and purity. Do not use denatured alcohol, which # contains other substances such as methanol or methylethylketone. # If the sample volume is greater than 140 ul, increase the amount of # ethanol proportionally (e.g., a 280 ul sample will require # 1120 ul of ethanol). In order to ensure efficient binding, it is # essential that the sample is mixed thoroughly with the ethanol # to yield a homogeneous solution. end end def lyse_samples_variable_volume(operations:, expert: false) msg = 'Method lyse_samples_variable_volume is not supported for ' \ 'Qiagen RNeasy Mini Kit' raise ProtocolError, msg end # @note adapted from `QIAampDSPViralRNAMiniKit` # @todo determine how much of the detail to keep or change def bind_rna(operations: [], sample_volume: DEFAULT_SAMPLE_VOLUME, expert: false) loading_volume, n_loads = loading_volume(sample_volume: sample_volume) show do title 'Add Samples to Columns' note "Get one #{COLUMN_LONG} for each sample, and copy the IDs " \ "from the #{LYSIS_TUBE_LONG}s to the #{COLUMN_SHORT}s." note "Carefully apply #{qty_display(loading_volume)} of each sample " \ "solution to the corresponding #{COLUMN_SHORT} " \ "(in #{WASH_TUBE_LONG}s) without wetting the rim." note "Close the lids, and centrifuge for #{CENTRIFUGE_TIME_AND_SPEED}." note "Place the #{COLUMN_SHORT}s into clean #{WASH_TUBE_SHORT}s, and " \ "discard the #{WASH_TUBE_SHORT}s containing the filtrate." warning 'Close each spin column in order to avoid cross-contamination ' \ 'during centrifugation.' # Centrifugation is performed at approximately 6000 x g in order to limit # microcentrifuge noise. Centrifugation at full speed will not affect the # yield or purity of the viral RNA. If the solution has not completely # passed through the membrane, centrifuge again at a higher speed # until all of the solution has passed through. separator note "Carefully open the #{COLUMN_SHORT}s, and repeat the " \ "loading #{n_loads - 1} more times until all of the lysate has " \ "been loaded onto the #{COLUMN_SHORT}s." end end def wash_rna(operations: [], expert: false) show do title 'Wash with Buffer RW1' note "Add 700 #{MICROLITERS} Buffer RW1 to each #{COLUMN_LONG}." note 'Close the lids gently, and centrifuge for ' \ "#{CENTRIFUGE_TIME_AND_SPEED}." warning "Carefully remove the #{COLUMN_SHORT}s from the collection " \ 'tubes so that the columns do not contact the flow-through.' note 'Empty the collection tubes completely.' note 'Reuse the collection tubes in the next step.' end show do title 'Wash twice with Buffer RPE' note "Add 500 #{MICROLITERS} Buffer RPE to each #{COLUMN_LONG}." note 'Close the lids gently, and centrifuge for ' \ "#{CENTRIFUGE_TIME_AND_SPEED}." note 'Empty the collection tubes.' note 'Reuse the collection tubes in the next step.' # Note: Buffer RPE is supplied as a concentrate. Ensure that ethanol is # added to Buffer RPE before use (see Things to do before starting). separator note "Add 500 #{MICROLITERS} Buffer RPE to the #{COLUMN_SHORT}." # The long centrifugation dries the spin column membrane, ensuring that # no ethanol is carried over during RNA elution. Residual ethanol may # interfere with downstream reactions. note "Close the lids gently, and centrifuge for 2 #{MINUTES} at " \ "#{qty_display(CENTRIFUGE_SPEED)}." warning "Carefully remove the #{COLUMN_SHORT}s from the collection " \ 'tubes so that the columns do not contact the flow-through.' note 'Discard the collection tubes.' separator # TODO: Should we do this step? note "Place each #{COLUMN_SHORT} in a new #{WASH_TUBE_LONG}, " \ "and discard the #{WASH_TUBE_SHORT}s containing the filtrate." # This centrifuge speed is meant to be different note "Centrifuge at full speed for 1 #{MINUTES}." end end def elute_rna(operations: [], expert: false) show do title 'Elute RNA' note "Get one #{ELUTION_TUBE_LONG} for each #{COLUMN_SHORT}, and copy " \ "the IDs from the #{COLUMN_SHORT}s to the #{ELUTION_TUBE_SHORT}s." note "Place each #{COLUMN_LONG} in a #{ELUTION_TUBE_SHORT}." note "Add #{qty_display(ELUTION_VOLUME)} RNAse-free water directly " \ 'to each spin column membrane.' note "Close the lids gently, and centrifuge for 1 #{MINUTES} at " \ "#{qty_display(CENTRIFUGE_SPEED)}." end end private # @todo generalize this for all sample lysis buffers def lysis_buffer_volume(sample_volume:) unless sample_volume[:units] == MICROLITERS raise ProtocolError, "Parameter :sample_volume must be in #{MICROLITERS}" end qty = sample_volume[:qty] { qty: qty, units: MICROLITERS } end def ethanol_volume(sample_volume:) qty = sample_volume[:qty] * 2.0 { qty: qty, units: MICROLITERS } end def loading_volume(sample_volume:) qty = sample_volume[:qty] qty += lysis_buffer_volume(sample_volume: sample_volume)[:qty] qty += ethanol_volume(sample_volume: sample_volume)[:qty] if qty <= 600 n_loads = 1 elsif qty <= 1200 n_loads = 2 elsif qty <= 1800 n_loads = 3 else raise ProtocolError, 'Parameter :sample_volume must be <= 1800 ' \ "#{MICROLITERS}" end qty /= n_loads.to_f [{ qty: qty, units: MICROLITERS }, n_loads] end end
aquariumbio/rna-extraction-kits
rna_extraction_kits/libraries/qiagenrnaextractionhelper/source.rb
# frozen_string_literal: true needs 'Standard Libs/Units' # Module for common methods and constants in Qiagen RNA extraction kits # # @author <NAME> <<EMAIL>> module QiagenRNAExtractionHelper include Units COLUMN_LONG = 'Qiagen spin column' COLUMN_SHORT = 'spin column' LYSIS_TUBE_LONG = 'lysis tube (LT)' LYSIS_TUBE_SHORT = 'LT' WASH_TUBE_LONG = "2 #{MILLILITERS} wash tube (WT)" WASH_TUBE_SHORT = 'WT' ELUTION_TUBE_LONG = 'elution tube (ET)' ELUTION_TUBE_SHORT = 'ET' # @note adapted from QIAamp DSP Viral RNA Mini Kit # @todo determine how much of the detail to keep or change def qiagen_notes_on_handling show do title "Handling of #{COLUMN_LONG.pluralize}" note 'Due to the sensitivity of nucleic acid amplification ' \ 'technologies, the following precautions are necessary when handling ' \ "#{COLUMN_LONG.pluralize} to avoid cross contamination between " \ 'sample preparations:' bullet "Carefully apply the sample or solution to the #{COLUMN_SHORT}. " \ "Pipet the sample into the #{COLUMN_SHORT} " \ 'without wetting the rim of the column.' bullet 'Always change pipet tips between liquid transfers. ' \ 'We recommend the use of aerosol-barrier pipet tips.' bullet "Avoid touching the #{COLUMN_SHORT} membrane with " \ 'the pipet tip.' bullet 'After all pulse-vortexing steps, briefly centrifuge the ' \ 'microcentrifuge tubes to remove drops from the inside of the lids.' bullet "Open only one #{COLUMN_SHORT} at a time, and take care " \ 'to avoid generating aerosols.' bullet 'Wear gloves throughout the entire procedure. In case of ' \ 'contact between gloves and sample, change gloves immediately.' end end end
aquariumbio/rna-extraction-kits
test/operation_types/rna_extraction_test/test.rb
<gh_stars>0 # frozen_string_literal: true class ProtocolTest < ProtocolTestBase def setup add_random_operations(3) # # Use this if you want to test alternative extraction kits # # Kits # # Qiagen RNeasy Mini Kit # # QIAamp DSP Viral RNA Mini Kit # # Test RNA Extraction Kit # # MagMAX Viral/Pathogen II Nucleic Acid Isolation Kit # s1 = Sample.find_by_name('Patient Sample 111') # s2 = Sample.find_by_name('Patient Sample 222') # s3 = Sample.find_by_name('Patient Sample 333') # [s1, s2, s3].each do |sample| # add_operation # .with_input('Specimen', sample) # .with_property( # 'Options', # '{ "rna_extraction_kit": "Qiagen RNeasy Mini Kit", "expert": false }' # ) # .with_output('Specimen', sample) # end end def analyze log('Hello from Nemo') assert_equal(@backtrace.last[:operation], 'complete') end end
aquariumbio/rna-extraction-kits
rna_extraction_kits/libraries/qiaampdspviralrnaminikit/source.rb
<filename>rna_extraction_kits/libraries/qiaampdspviralrnaminikit/source.rb # frozen_string_literal: true needs 'RNA Extraction Kits/QiagenRNAExtractionHelper' # Module for QIAamp DSP Viral RNA Mini Kit # # @author <NAME> <<EMAIL>> module QIAampDSPViralRNAMiniKit include QiagenRNAExtractionHelper NAME = 'QIAamp DSP Viral RNA Mini Kit' COLUMN_LONG = 'QIAamp Mini spin column' MIN_SAMPLE_VOLUME = { qty: 140, units: MICROLITERS }.freeze DEFAULT_SAMPLE_VOLUME = MIN_SAMPLE_VOLUME WASH_VOLUME = { qty: 500, units: MICROLITERS }.freeze CENTRIFUGE_SPEED = { qty: 6000, units: TIMES_G }.freeze CENTRIFUGE_TIME = { qty: 1, units: MINUTES }.freeze CENTRIFUGE_TIME_AND_SPEED = "#{Units.qty_display(CENTRIFUGE_TIME)} at " \ "#{Units.qty_display(CENTRIFUGE_SPEED)}" def prepare_materials show do title 'Things to do before starting' bullet "Equilibrate samples to room temperature (15-25#{DEGREES_C})" bullet 'Equilibrate Buffer AVE to room temperature' # TODO: Need some way of indicating this has been done bullet 'Check that Buffer AW1 and Buffer AW2 have been prepared ' \ 'according to the instructions' # TODO: Need some way of indicating this has been done bullet 'Add carrier RNA reconstituted in Buffer AVE to Buffer AVL ' \ 'according to the instructions' end end def notes_on_handling qiagen_notes_on_handling end # @todo will we be working with a different sample volume for each operation? # @todo make use_operations do this^ def lyse_samples_constant_volume(sample_volume: DEFAULT_SAMPLE_VOLUME, expert: false) # TODO: Move this logic up to the calling method if sample_volume[:qty] < MIN_SAMPLE_VOLUME[:qty] msg = "Sample volume must be > #{qty_display(MIN_SAMPLE_VOLUME)}" raise ProtocolError, msg end buffer_volume = lysis_buffer_volume(sample_volume: sample_volume) ethanol_volume = ethanol_volume(sample_volume: sample_volume) show do title 'Lyse Samples' # TODO: Add Pipettor module note "Get one #{LYSIS_TUBE_LONG} for each sample, and copy the IDs " \ "from the samples to the #{LYSIS_TUBE_SHORT}s." note "Pipet #{qty_display(buffer_volume)} of prepared Buffer AVL " \ "(containing carrier RNA) into each #{LYSIS_TUBE_SHORT}." # If the sample volume is larger than 140 ul, increase the amount of # Buffer AVL-carrier RNA proportionally (e.g., a 280 ul sample will # require 1120 ul Buffer AVL-carrier RNA) and use a larger tube. note "Transfer #{qty_display(sample_volume)} of each sample to the " \ "corresponding #{LYSIS_TUBE_SHORT}." # TODO: Should this be kept in? note "Mix by pulse-vortexing for 15 #{SECONDS}." warning 'To ensure efficient lysis, it is essential that the sample ' \ 'is mixed thoroughly with Buffer AVL to yield a homogeneous solution' # Frozen samples that have only been thawed once can also be used. # TODO: Should this be kept in? note "Incubate at room temperature (15-25#{DEGREES_C}) for 10 #{MINUTES}" end show do title 'Add Ethanol' note "Briefly centrifuge the #{LYSIS_TUBE_LONG}s to remove drops from " \ 'the inside of the lids.' # TODO: provision ethanol at beginning and use shorter name note "Add #{qty_display(ethanol_volume)} ethanol (96-100%) to each " \ 'sample, and mix by pulse-vortexing for >15 seconds. ' \ 'After mixing, briefly centrifuge the tubes to remove drops from ' \ 'inside the lids.' # Only ethanol should be used since other alcohols may result in # reduced RNA yield and purity. Do not use denatured alcohol, which # contains other substances such as methanol or methylethylketone. # If the sample volume is greater than 140 ul, increase the amount of # ethanol proportionally (e.g., a 280 ul sample will require # 1120 ul of ethanol). In order to ensure efficient binding, it is # essential that the sample is mixed thoroughly with the ethanol # to yield a homogeneous solution. end end def lyse_samples_variable_volume(operations:, expert: false) msg = 'Method lyse_samples_variable_volume is not supported for ' \ 'QIAamp DSP Viral RNA Mini Kit' raise ProtocolError, msg end def bind_rna(operations: [], sample_volume: DEFAULT_SAMPLE_VOLUME, expert: false) loading_volume, n_loads = loading_volume(sample_volume: sample_volume) show do title 'Add Samples to Columns' note "Get one #{COLUMN_LONG} for each sample, and copy the IDs " \ "from the #{LYSIS_TUBE_LONG}s to the #{COLUMN_SHORT}s." note "Carefully apply #{qty_display(loading_volume)} of each sample " \ " solution to the corresponding #{COLUMN_SHORT} " \ "(in #{WASH_TUBE_LONG}s) without wetting the rim." note "Close the lids, and centrifuge for #{CENTRIFUGE_TIME_AND_SPEED}." \ "Place the #{COLUMN_SHORT}s into clean" \ "#{WASH_TUBE_SHORT}s, and discard the old #{WASH_TUBE_SHORT}s " \ 'containing the filtrate.' warning 'Close each spin column in order to avoid cross-contamination ' \ 'during centrifugation.' # Centrifugation is performed at approximately 6000 x g in order to limit # microcentrifuge noise. Centrifugation at full speed will not affect the # yield or purity of the viral RNA. If the solution has not completely # passed through the membrane, centrifuge again at a higher speed # until all of the solution has passed through. separator note "Carefully open the #{COLUMN_SHORT}s, and repeat the " \ "loading #{n_loads - 1} more times until all of the lysate has " \ "been loaded onto the #{COLUMN_SHORT}s." end end def wash_rna(operations: [], expert: false) show do title 'Wash with Buffer AW1' note "Carefully open the #{COLUMN_LONG}, and add " \ "#{qty_display(WASH_VOLUME)} Buffer AW1." note 'Close the lids gently, and centrifuge for ' \ "#{CENTRIFUGE_TIME_AND_SPEED}." note "Place each #{COLUMN_SHORT} into a clean #{WASH_TUBE_LONG}, " \ "and discard the #{WASH_TUBE_SHORT}s containing the filtrate." # It is not necessary to increase the volume of Buffer AW1 even if the # original sample volume was larger than 140 ul. end show do title 'Wash with Buffer AW2' note "Carefully open the #{COLUMN_LONG}s, and add " \ "#{qty_display(WASH_VOLUME)} Buffer AW2." # This centrifuge speed is meant to be different note 'Close the cap and centrifuge at full speed ' \ "(approximately 20,000 #{TIMES_G}) for 3 #{MINUTES}." separator note "Place each #{COLUMN_SHORT} into a new #{WASH_TUBE_LONG}, " \ "and discard the #{WASH_TUBE_SHORT}s containing the filtrate." # This centrifuge speed is meant to be different note "Centrifuge at full speed for 1 #{MINUTES}." end end def elute_rna(operations: [], expert: false) show do title 'Elute RNA' note "Place each #{COLUMN_LONG} into a clean #{ELUTION_TUBE_LONG}." note "Discard the #{WASH_TUBE_SHORT}s containing the filtrate." note "Carefully open the #{COLUMN_SHORT}s and add " \ "60 #{MICROLITERS} of Buffer AVE equilibrated to room temperature." note "Close the cap, and incubate at room temperature for >1 #{MINUTES}." note "Centrifuge for #{CENTRIFUGE_TIME_AND_SPEED}." end end private def lysis_buffer_volume(sample_volume:) unless sample_volume[:units] == MICROLITERS raise ProtocolError, "Parameter :sample_volume must be in #{MICROLITERS}" end qty = sample_volume[:qty] * 560 / 140 { qty: qty, units: MICROLITERS } end def ethanol_volume(sample_volume:) qty = lysis_buffer_volume(sample_volume: sample_volume)[:qty] { qty: qty, units: MICROLITERS } end # TODO: Is this right? def loading_volume(sample_volume:) qty = 630 n_loads = 2 [{ qty: qty, units: MICROLITERS }, n_loads] end end
aquariumbio/rna-extraction-kits
rna_extraction_kits/libraries/supportedrnaextractionkits/source.rb
# frozen_string_literal: true needs 'RNA Extraction Kits/TestRNAExtractionKit' needs 'RNA Extraction Kits/QIAampDSPViralRNAMiniKit' needs 'RNA Extraction Kits/QiagenRNeasyMiniKit' # Module for enumerating supported RNA extraction kits # # @author <NAME> <<EMAIL>> module SupportedRNAExtractionKits # Extend the module with the correct methods based on the kit name # # @param name [String] the name of the kit # @return [void] def set_kit(name:) case name when TestRNAExtractionKit::NAME extend TestRNAExtractionKit when QIAampDSPViralRNAMiniKit::NAME extend QIAampDSPViralRNAMiniKit when QiagenRNeasyMiniKit::NAME extend QiagenRNeasyMiniKit else raise ProtocolError, "Unrecognized RNA Extraction Kit: #{name}" end end end
aquariumbio/rna-extraction-kits
rna_extraction_kits/libraries/testrnaextractionkit/source.rb
# frozen_string_literal: true needs 'Standard Libs/Units' # Minimal RNA Extraction Kit Module for testing # # @author <NAME> <<EMAIL>> module TestRNAExtractionKit include Units NAME = 'Test RNA Extraction Kit' MIN_SAMPLE_VOLUME = { qty: 140, units: MICROLITERS }.freeze DEFAULT_SAMPLE_VOLUME = MIN_SAMPLE_VOLUME def prepare_materials show do title 'Things to do before starting' end end def notes_on_handling show do title 'Handling Materials' end end def lyse_samples_constant_volume(sample_volume:, expert: false) show do title 'Lyse Samples Constant Volume' note "Sample volume: #{qty_display(sample_volume)}" end end def lyse_samples_variable_volume(operations:, expert: false) show do title 'Lyse Samples Variable Volume' operations.each { |op| note "Sample volume: #{sample_volume(op)}" } end end def bind_rna(operations: [], sample_volume: DEFAULT_SAMPLE_VOLUME, expert: false) show do title 'Add Samples to Columns' end end def wash_rna(operations: [], expert: false) show do title 'Wash with Buffer' end end def elute_rna(operations: [], expert: false) show do title 'Elute RNA' end end end
aquariumbio/rna-extraction-kits
rna_extraction_kits/libraries/rnaextractionkits/source.rb
<filename>rna_extraction_kits/libraries/rnaextractionkits/source.rb # frozen_string_literal: true needs 'RNA Extraction Kits/SupportedRNAExtractionKits' # Module for switching among several different RNA extraction kits # # @author <NAME> <<EMAIL>> module RNAExtractionKits include SupportedRNAExtractionKits # Run the protocol defined by the kit # # @note if `sample_volume` is provided, then all samples will be run # using that volume of sample # @note if `sample_volume` is not provided, but `operations` are, then # the protocol will look for sample_volumes assigned to the `Operations` # @note if neither `sample_volume` nor `operations` are provided, then # all samples will be run using `DEFAULT_SAMPLE_VOLUME` # @param operations [OperationList] the operations to run # @param sample_volume [Hash] the volume as a Hash in the format # `{ qty: 140, units: MICROLITERS }` # @return [void] def run_rna_extraction_kit(operations: [], sample_volume: nil, expert: false) prepare_materials notes_on_handling unless expert if sample_volume lyse_samples_constant_volume(sample_volume: sample_volume, expert: expert) elsif operations.present? lyse_samples_variable_volume(operations: operations, expert: expert) else lyse_samples_constant_volume(expert: expert) end bind_rna( operations: operations, sample_volume: sample_volume, expert: expert ) wash_rna(operations: operations, expert: expert) elute_rna(operations: operations, expert: expert) end end
JuniorBoaventura/react-native-keyboard-manager
RNKeyboardManager.podspec
require 'json' version = JSON.parse(File.read('package.json'))["version"] Pod::Spec.new do |s| s.name = "RNKeyboardManager" s.version = version s.description = <<-DESC This library allows to prevent issues of keyboard sliding up and cover on React-Native iOS projects DESC s.homepage = "https://github.com/douglasjunior/react-native-keyboard-manager" s.summary = "A <ReactNativeKeyboardManager /> component for react-native" s.license = "MIT" s.authors = "<NAME>" s.source = { :git => "https://github.com/douglasjunior/react-native-keyboard-manager.git", :tag => "v#{s.version}" } s.platform = :ios, "8.0" s.preserve_paths = 'README.md', 'package.json', '*.js' s.source_files = 'ios/ReactNativeKeyboardManager/**/*.{h,m}' s.dependency 'React' s.dependency 'IQKeyboardManager' end
mneumann/rust-smtp
test.rb
<reponame>mneumann/rust-smtp require 'net/smtp' msgstr = <<END_OF_MESSAGE From: <NAME> <<EMAIL>> To: Destination Address <<EMAIL>> Subject: test message Date: Sat, 23 Jun 2001 16:26:43 +0900 Message-Id: <<EMAIL>> This is a test message. END_OF_MESSAGE Net::SMTP.start('127.0.0.1', 2525, 'mail.from.domain') do |smtp| smtp.send_message msgstr, '<EMAIL>', '<EMAIL>' end
lighty/oas_divider
lib/oas_divider/paths_object.rb
module OasDivider class PathsObject attr_accessor :path, :path_item_objects def initialize(path, path_item_objects) @path = path @path_item_objects = path_item_objects end def to_file make_directory convert_ref YAML.dump(path_item_objects, File.open( File.join(directory, file_name) , 'w') ) end def make_directory FileUtils.mkdir_p( directory ) rescue => e puts "path: #{@path}" throw e end def interlevel_directory @path.split('/').length > 2 ? @path.split('/')[1..-2].map {|dir| dir.gsub(/[{}]/,"")} : '' end def directory File.join( 'paths' , interlevel_directory) end def file_name "#{@path.split('/').pop.gsub(/[{}]/,"")}.yml" end def ref File.join(directory, file_name) end def convert_ref RelativeDocumentReferencer.execute(path_item_objects, 1 + interlevel_directory.size) end end end
lighty/oas_divider
lib/oas_divider/relative_document_referencer.rb
<reponame>lighty/oas_divider module OasDivider class RelativeDocumentReferencer def self.execute(root, depth) new(root, depth).execute end def initialize(root, depth) @root = root @depth = depth end def execute lookup(root) root end # hashで、keyが$refならconvert # hashかarrayならlookup # そうでないならなにもしない def lookup(object) if object.is_a? Array object.each { |value| lookup(value) if value.is_a?(Hash) || value.is_a?(Array) } else object.each do |key, value| set_converted_value(object, key, value) if key === "$ref" lookup(value) if value.is_a?(Hash) || value.is_a?(Array) end end end def set_converted_value(object, key, value) object[key] = convert(value) end def convert(ref) # componentから取得することしか考えない if ref.split('/')[2] === 'schemas' "../" * depth + "#{ref.split('/')[1..3].join('/')}.yml" else "../" * depth + "#{ref.split('/')[1..2].join('/')}.yml#/#{ref.split('/')[3]}" end end private attr :root, :depth end end
lighty/oas_divider
lib/oas_divider/schema_object.rb
module OasDivider class SchemaObject attr_accessor :schema_name, :schema_object def initialize(schema_name, schema_object) @schema_name = schema_name @schema_object = schema_object end def to_file convert_ref YAML.dump(schema_object, File.open( File.join(directory, file_name) , 'w') ) end def directory 'components/schemas' end def file_name "#{schema_name}.yml" end def ref File.join(directory, file_name) end def convert_ref RelativeDocumentReferencer.execute(schema_object, 2) end end end
lighty/oas_divider
lib/oas_divider.rb
require 'oas_divider/version' require 'yaml' require 'fileutils' require 'oas_divider/components_object_field_object' require 'oas_divider/paths_object' require 'oas_divider/relative_document_referencer' require 'oas_divider/schema_object' module OasDivider class Cli def initialize(file_name) @file_name = file_name end def divide load_file_as_open_api_object save_divided_files save_open_api_object_as_root_file end private def save_divided_files open_api_object.keys.each do |open_api_object_field| if open_api_object_field === "paths" FileUtils.mkdir_p('paths') paths_objects = open_api_object[open_api_object_field] paths_objects.keys.each do |path| path_object = PathsObject.new(path, paths_objects[path]) # 一つのpathオブジェクト。postなどがキー path_object.to_file open_api_object[open_api_object_field][path] = { "$ref" => path_object.ref } end end if open_api_object_field === "components" FileUtils.mkdir_p('components') components_objects = open_api_object[open_api_object_field] components_objects.keys.each do |components_object_field| if components_object_field === 'schemas' FileUtils.mkdir_p('components/schemas') schmas = components_objects[components_object_field] schmas.keys.each do |schema_name| schema_object = SchemaObject.new(schema_name, schmas[schema_name]) schema_object.to_file open_api_object[open_api_object_field][components_object_field][schema_name] = { "$ref" => schema_object.ref } end else field_object = ComponentsObjectFieldObject.new(components_object_field, components_objects[components_object_field]) field_object.to_file open_api_object[open_api_object_field][components_object_field] = { "$ref" => field_object.ref } end end end end end def load_file_as_open_api_object self.open_api_object = YAML.load_file(file_name) end def save_open_api_object_as_root_file YAML.dump(open_api_object, File.open('swagger_root.yml', 'w')) end attr_accessor :file_name, :open_api_object end end
lighty/oas_divider
spec/oas_divider_spec.rb
<filename>spec/oas_divider_spec.rb RSpec.describe OasDivider do it "has a version number" do expect(OasDivider::VERSION).not_to be nil end let(:oas_divider) { OasDivider::Cli.new('spec/fixtures/openapi.yaml') } before { oas_divider.divide } after { FileUtils.rm_r %w(swagger_root.yml components paths) } # TODO 出力ディレクトリ指定できるようにしないと危険 specify 'ファイルが作成されること', :aggrigate_failures do expect(File).to exist('swagger_root.yml') end end
lighty/oas_divider
lib/oas_divider/components_object_field_object.rb
module OasDivider class ComponentsObjectFieldObject attr_accessor :field_name, :field_object def initialize(field_name, field_object) @field_name = field_name @field_object = field_object end def to_file convert_ref YAML.dump(field_object, File.open( File.join(directory, file_name) , 'w') ) end def directory 'components' end def file_name "#{field_name}.yml" end def ref File.join(directory, file_name) end def convert_ref RelativeDocumentReferencer.execute(field_object, 1) end end end
NStephenson/smartvote_sinatra_assessment
app/models/issue.rb
<filename>app/models/issue.rb<gh_stars>0 class Issue < ActiveRecord::Base has_many :reactions has_many :voters, through: :reactions has_many :candidates, through: :reactions def self.issue_categories categories = [] all.map do |issue| if !categories.include?(issue.category) categories << issue.category end end categories end def find_reaction(person) if person.class == Candidate reactions.find do |reaction| reaction.candidate_id == person.id end elsif person.class == Voter reactions.find do |reaction| reaction.voter_id == person.id end end end def candidate_reactions reactions.select { |reaction| reaction.candidate } end end
NStephenson/smartvote_sinatra_assessment
app/models/voter.rb
<filename>app/models/voter.rb class Voter < ActiveRecord::Base has_many :reactions has_many :issues, through: :reactions has_many :candidates, through: :reactions has_secure_password def best_candidate reactions.each do |reaction| end end end
NStephenson/smartvote_sinatra_assessment
app/controllers/candidates_controller.rb
class CandidatesController < ApplicationController get '/candidates' do @candidates = Candidate.all erb :'candidates/index' end get '/candidates/:id' do @candidate = Candidate.find(params[:id]) erb :'candidates/show' end end
NStephenson/smartvote_sinatra_assessment
app/controllers/voters_controller.rb
<gh_stars>0 class VotersController < ApplicationController get '/voters' do @voters = Voter.all erb :'voters/index' end get '/voters/:id' do @voter = Voter.find(params[:id]) erb :'voters/show' end get '/signup' do if logged_in? redirect to '/reactions' else erb :'voters/new' end end post '/signup' do if !Voter.find_by(username: params[:username]) && !Voter.find_by(email: params[:email]) voter = Voter.new(params) else flash[:error] = "This username or email is is taken" voter = Voter.new end if voter.save session[:id] = voter.id redirect '/reactions' else erb :'voters/new' end end get '/login' do if logged_in? redirect '/reactions' else erb :'voters/login' end end post '/login' do voter = Voter.find_by(username: params[:username]) if !!voter && voter.authenticate(params[:password]) session[:id] = voter.id end redirect "/reactions" end get '/logout' do session.clear redirect '/' end end
NStephenson/smartvote_sinatra_assessment
app/controllers/issues_controller.rb
class IssuesController < ApplicationController get '/issues' do @issues = Issue.all erb :'issues/index' end get '/issues/:id' do @issue = Issue.find(params[:id]) erb :'issues/show' end end
NStephenson/smartvote_sinatra_assessment
app/controllers/reactions_controller.rb
require 'rack-flash' class ReactionsController < ApplicationController use Rack::Flash get '/reactions' do @reactions = Reaction.all erb :'reactions/index' end get '/issues/:id/addreaction' do if logged_in? @issue = Issue.find(params[:id]) erb :'reactions/new' else redirect '/login' end end post '/reactions' do if !params[:text].empty? && params[:agreement].to_i.between?(1,5) && logged_in? @reaction = Reaction.create( issue_id: params[:issue_id].to_i, voter_id: current_user.id, text: params[:text], agreement: params[:agreement] ) flash[:message] = "Reaction successfully created!" redirect '/reactions' end flash[:message] = "Invalid data!" redirect '/reactions' end get '/reactions/:id' do reaction = Reaction.find(params[:id]) @issue = reaction.issue erb :'issues/show' end get '/reactions/:id/edit' do @reaction = Reaction.find(params[:id]) if logged_in? && @reaction.voter_id == current_user.id erb :'reactions/edit' else redirect "/reactions/#{params[:id]}" end end patch '/reactions/:id' do @reaction = Reaction.find(params[:id]) if !params[:text].empty? && params[:agreement].to_i.between?(1,5) @reaction.update(text: params[:text], agreement: params[:agreement].to_i) @reaction.save flash[:message] = "You've successfully flip-flopped on your position." else flash[:message] = "Invalid data. Please try again." end redirect "/reactions/#{params[:id]}/edit" end delete '/reactions/:id' do @reaction = Reaction.find(params[:id]) if @reaction.voter.id == current_user.id @reaction.delete flash[:message] = "You've successfully deleted your position." redirect "/reactions" else flash[:message] = "You can't do that! That's not even your reaction!" redirect "/reactions" end end end
NStephenson/smartvote_sinatra_assessment
config.ru
require './config/environment' require 'rack-flash' if ActiveRecord::Migrator.needs_migration? raise 'Migrations are pending. Run `rake db:migrate` to resolve the issue.' end use Rack::MethodOverride use VotersController use CandidatesController use IssuesController use ReactionsController run ApplicationController
NStephenson/smartvote_sinatra_assessment
app/models/candidate.rb
class Candidate < ActiveRecord::Base has_many :reactions has_many :voters, through: :reactions has_many :issues, through: :reactions def issues_for reactions.each_with_object([]) do |reaction, arr| if reaction.agreement > 3 arr << reaction.issue end end end def issues_against reactions.each_with_object([]) do |reaction, arr| if reaction.agreement < 3 arr << reaction.issue end end end end
NStephenson/smartvote_sinatra_assessment
app/models/reaction.rb
class Reaction < ActiveRecord::Base belongs_to :voter belongs_to :candidate belongs_to :issue def agreeance case agreement when 1 "Strongly Disagree" when 2 "Disagree" when 3 "Neutral/Undeclared" when 4 "Agree" when 5 "Strongly Agree" end end end
NStephenson/smartvote_sinatra_assessment
db/migrate/20160309002330_create_reactions.rb
class CreateReactions < ActiveRecord::Migration def change create_table :reactions do |t| t.text :text t.integer :agreement t.integer :issue_id t.integer :candidate_id t.integer :voter_id end end end
chrisb/character-title-gen
lib/character_titles.rb
require 'active_support/all' require 'character_titles/version' require 'character_titles/helpers' require 'character_titles/place' require 'character_titles/evil' require 'character_titles/good' require 'character_titles/neutral' class String def titleize_for_character self.strip.titleize.gsub('Of', 'of').gsub('The', 'the').gsub(' , ', ', ') end end
chrisb/character-title-gen
lib/character_titles/evil.rb
module CharacterTitles module Evil module_function extend Helpers SILLY = false BODY_PARTS_SINGULAR = %w(anus blood flesh skin fat death eye sight) BODY_PARTS = %w(intestine colon gonad skull leg arm body head gut beast heart liver) VIOLENT_VERBS_AS_NOUNS = %w(vommitter cooker roaster punisher mutalator disfigurer clawer disembowler crusher masher ravisher banisher killer grasper tearer flayer eater ripper impaler chewer sucker severer wrencher sapper reamer walker feaster devourer destroyer tormentor defiler mincer) ADJECTIVES = %w(evil dark rotting putrid forgotten terrible horrible nasty sickening putrifying banished outlawed) NOUNS = %w(scourage terror horror ghoul ghost beast outlaw criminal demon) def qualifier "#{chance_of 'the'} #{NOUNS.sample} of #{CharacterTitles::Place.generate}" end def descriptor body_part = (BODY_PARTS_SINGULAR + BODY_PARTS).sample singular = BODY_PARTS_SINGULAR.include? body_part !singular && rand(2) == 1 ? "#{VIOLENT_VERBS_AS_NOUNS.sample} of #{body_part.pluralize}" : "#{body_part}#{word_separator}#{VIOLENT_VERBS_AS_NOUNS.sample}" end def generate [chance_of('the'), chance_of(ADJECTIVES), descriptor, chance_of(", #{qualifier}", 0.5)].compact.join(' ').titleize_for_character end end end
chrisb/character-title-gen
lib/character_titles/good.rb
<reponame>chrisb/character-title-gen module CharacterTitles module Good module_function extend Helpers NOUNS = %w(light wonder prosperity goodness truth) VERBS_AS_NOUNS = %w(bringer restorer bearer guardian savior protector) ANTI_VERBS_AS_NOUNS = %w(vanquisher slayer destroyer cleanser healer remover) def qualifier "#{chance_of 'the'}#{ANTI_VERBS_AS_NOUNS.sample} of #{ CharacterTitles::Evil::NOUNS.sample.pluralize}" end def title "#{chance_of 'the'} #{NOUNS.sample}#{chance_of '-', 0.5}#{VERBS_AS_NOUNS.sample}" end def generate "#{title} #{chance_of qualifier, 0.5}".titleize_for_character end end end
chrisb/character-title-gen
lib/character_titles/place.rb
module CharacterTitles module Place module_function ADJECTIVES = %w(northern southern western eastern cold wintery snowy rugged dark crimson red bloody haunted) MODIFIERS = %w(world land realm) PLACES = %w(winter plains south east north west caves caverns towers) PLACES_NEEDING_MODIFIER = %w(under over hinter grass water wet) def should_modify? rand(3) == 1 end def should_be_proper? rand(4) != 1 end def should_add_adjective? rand(3) == 1 end def place_with_modifier PLACES_NEEDING_MODIFIER.sample + MODIFIERS.sample end def place_name PLACES.sample end def generate place = should_modify? ? place_with_modifier : place_name place = "#{ADJECTIVES.sample} #{place}" if should_add_adjective? "#{'the' if should_be_proper?} #{place}".strip end end end
chrisb/character-title-gen
lib/character_titles/neutral.rb
<filename>lib/character_titles/neutral.rb module CharacterTitles module Neutral module_function extend Helpers PREFIXES = %w(byr dy mi beo tyr) POSTFIXES = %w(dren bor dun mar del lad ar gren grad gard born bar bel wren rend mel dar den ful ren) ANIMALS = %w(wolf dragon bear beast) PROFESSIONS = %w(guard hunter smith bard fletcher) NATURE = %w(cliff storm wind sand earth) ADJECTIVES = %w(stalwart honest faithful haggard tireless) NOUNS = PROFESSIONS + NATURE + ANIMALS def first_name (PREFIXES.sample + POSTFIXES.sample).titleize_for_character end def full_name "#{first_name} #{surname}".titleize_for_character end def object NOUNS.sample + chance_of(NOUNS, 0.2).to_s end def prefix rand(3) == 1 ? PREFIXES.sample : '' end def title "#{chance_of 'the', 0.2} #{chance_of ADJECTIVES} #{PROFESSIONS.sample} of #{CharacterTitles::Place.generate}".titleize_for_character end def surname (prefix + object + POSTFIXES.sample).titleize_for_character end def generate_random "#{full_name}#{separator}#{one_of title, Evil.generate, Good.generate}" end end end
chrisb/character-title-gen
lib/character_titles/helpers.rb
module CharacterTitles module Helpers module_function def one_of(*args) args.sample end def chance_of(obj, chance = 0.3) obj = obj.sample if obj.is_a?(Array) rand < chance ? obj : nil end def word_separator ['', '-', ' '].sample end def separator(include_none = false) [', ', ' - ', ': '].concat(include_none ? [''] : []).sample end end end
talentnest/compendium
app/classes/compendium/presenters/base.rb
module Compendium::Presenters class Base def initialize(template, object) @object = object @template = template end def to_s "#<#{self.class.name}:0x00#{'%x' % (object_id << 1)}>" end private def self.presents(name) define_method(name) do @object end end def method_missing(*args, &block) return @template.send(*args, &block) if @template.respond_to?(args.first) super end def respond_to_missing?(*args) return true if @template.respond_to?(*args) super end end end
talentnest/compendium
app/classes/compendium/presenters/csv.rb
require 'csv' module Compendium::Presenters class CSV < Table def initialize(object, &block) super(nil, object, &block) end def render ::CSV.generate do |csv| csv << headings.map{ |_, val| formatted_heading(val) } records.each do |row| csv << row.map{ |key, val| formatted_value(key, val) } end if has_totals_row? totals[totals.keys.first] = translate(:total) csv << totals.map do |key, val| formatted_value(key, val) unless settings.skipped_total_cols.include?(key.to_sym) end end end end private def settings_class Compendium::Presenters::Settings::Table end end end
talentnest/compendium
spec/result_set_spec.rb
<reponame>talentnest/compendium require 'compendium/result_set' describe Compendium::ResultSet do describe "#initialize" do subject{ described_class.new(results).records } context "when given an array" do let(:results) { [1, 2, 3] } it { should == [1, 2, 3] } end context "when given an array of hashes" do let(:results) { [{one: 1}, {two: 2}] } it { should == [{"one" => 1}, {"two" => 2}] } its(:first) { should be_a ActiveSupport::HashWithIndifferentAccess } end context "when given a hash" do let(:results) { { one: 1, two: 2 } } it { should == { one: 1, two: 2 } } end context "when given a scalar" do let(:results) { 3 } it { should == [3] } end end end
talentnest/compendium
spec/presenters/chart_spec.rb
require 'spec_helper' require 'compendium/presenters/chart' describe Compendium::Presenters::Chart do let(:template) { double('Template', protect_against_forgery?: false, request_forgery_protection_token: :authenticity_token, form_authenticity_token: "<KEY>").as_null_object } let(:query) { double('Query', name: 'test_query', results: results, ran?: true, options: {}).as_null_object } let(:results) { Compendium::ResultSet.new([]) } before do described_class.any_instance.stub(:provider) { double('ChartProvider') } described_class.any_instance.stub(:initialize_chart_provider) end describe '#initialize' do context 'when all params are given' do subject{ described_class.new(template, query, :pie, :container) } its(:data) { should == results.records } its(:container) { should == :container } end context 'when container is not given' do subject{ described_class.new(template, query, :pie) } its(:data) { should == results.records } its(:container) { should == 'test_query' } end context "when options are given" do before { results.stub(:records) { { one: [] } } } subject{ described_class.new(template, query, :pie, index: :one) } its(:data) { should == results.records[:one] } its(:container) { should == 'test_query' } end context "when the query has not been run" do before { query.stub(ran?: false, url: '/path/to/query.json') } subject{ described_class.new(template, query, :pie, params: { foo: 'bar' }) } its(:data) { should == '/path/to/query.json' } its(:params) { should == { report: { foo: 'bar' } } } context "when CSRF protection is enabled" do before { template.stub(protect_against_forgery?: true) } its(:params) { should include authenticity_token: "<KEY>IJ" } end context "when CSRF protection is disabled" do its(:params) { should_not include authenticity_token: "ABCDEF<PASSWORD>" } end end end describe '#remote?' do it 'should be true if options[:remote] is set to true' do described_class.new(template, query, :pie, remote: true).should be_remote end it 'should be true if the query has not been run yet' do query.stub(run?: false) described_class.new(template, query, :pie).should_be_remote end it 'should be false otherwise' do described_class.new(template, query, :pie).should_not be_remote end end end
talentnest/compendium
lib/compendium/open_hash.rb
<gh_stars>0 require 'active_support/hash_with_indifferent_access' module Compendium class OpenHash < ::ActiveSupport::HashWithIndifferentAccess class << self def [](hash = {}) new(hash) end end def dup self.class.new(self) end protected def convert_value(value) if value.is_a? Hash Params[value].tap do |oh| oh.each do |k, v| oh[k] = convert_value(v) if v.is_a? Hash end end elsif value.is_a?(Array) value.dup.replace(value.map { |e| convert_value(e) }) else value end end def method_missing(name, *args, &block) method = name.to_s case method when %r{.=$} super unless args.length == 1 return self[method[0...-1]] = args.first when %r{.\?$} super unless args.empty? return self.key?(method[0...-1].to_sym) when %r{^_.} super unless args.empty? return self[method[1..-1]] if self.key?(method[1..-1].to_sym) else return self[method] if key?(method) || !respond_to?(method) end super end def respond_to_missing?(name, include_private = false) method = name.to_s case method when %r{.[=?]$} return true if self.key?(method[0...-1]) when %r{^_.} return true if self.key?(method[1..-1]) end super end end end
talentnest/compendium
lib/compendium/engine/mount.rb
module ActionDispatch module Routing class Mapper class ExportRouter def matches?(request) request.params[:export].present? end end def mount_compendium(options = {}) scope options[:at], controller: options.fetch(:controller, 'compendium/reports'), as: 'compendium_reports' do get ':report_name', action: :setup, constraints: { format: :html }, as: 'setup' match ':report_name/export', action: :export, as: 'export', via: [:get, :post] post ':report_name(/:query)', constraints: ExportRouter.new, action: :export, as: 'export_post' match ':report_name(/:query)', action: :run, as: 'run', via: [:get, :post] root action: :index, as: 'root' end end end end end