repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
nerdgeschoss/pixelpress
|
lib/generators/pixelpress/printer/templates/initializer.rb
|
Rails.application.config.autoload_paths << Rails.root.join('app', 'printers')
Rails.application.config.autoload_paths << Rails.root.join('spec', 'printer', 'previews') if Rails.env.development?
|
nerdgeschoss/pixelpress
|
lib/pixelpress.rb
|
require 'pixelpress/version'
require 'pixelpress/base'
require 'pixelpress/document'
require 'pixelpress/engine' if defined? Rails
require 'pixelpress/preview' if defined? Rails
module Pixelpress
end
|
nerdgeschoss/pixelpress
|
spec/lib/generators/test/generator_spec/test_destination/app/printers/auth/user_printer.rb
|
class Auth::UserPrinter < ApplicationPrinter
def user_data
#put your code here, if you want :)
end
end
|
nerdgeschoss/pixelpress
|
spec/spec_helper.rb
|
<filename>spec/spec_helper.rb<gh_stars>1-10
require 'bundler/setup'
require 'pixelpress'
require 'pixelpress/base'
require 'pry'
require 'active_model'
require 'weasyprint'
require 'generator_spec'
require 'rails/generators'
require 'rails/generators/named_base'
require 'generators/pixelpress/printer/printer_generator'
require 'pathname'
RSpec.configure do |config|
config.example_status_persistence_file_path = '.rspec_status'
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
def spec_root
File.dirname(__FILE__)
end
|
nerdgeschoss/pixelpress
|
lib/generators/rspec/templates/preview.rb
|
class <%= class_name %>Preview < Pixelpress::Preview<% passed_methods.each do |m| %>
def <%= m %>
<%= class_name %>Printer.<%= m %>
end<% end %>
end
|
nerdgeschoss/pixelpress
|
lib/pixelpress/renderers/weasyprint_renderer.rb
|
<filename>lib/pixelpress/renderers/weasyprint_renderer.rb
require 'weasyprint'
class Pixelpress::WeasyPrintRenderer
def render(html)
WeasyPrint.new(html).to_pdf
end
end
|
nerdgeschoss/pixelpress
|
lib/generators/pixelpress/printer/printer_generator.rb
|
module Pixelpress
module Generators
class PrinterGenerator < ::Rails::Generators::NamedBase
source_root File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
argument :passed_methods, type: :array, default: [], required: false, banner: 'method_name1 method_name2 ...'
check_class_collision suffix: 'Printer'
hook_for :test_framework
def create_custom_printer
template 'application_printer.rb', 'app/printers/application_printer.rb' unless Rails.root.join('app/printers/application_printer.rb').exist?
route 'mount Pixelpress::Engine => "rails" if Rails.env.development?' unless engine_mounted?
template 'printer.pdf.erb', 'app/views/layouts/printer.pdf.erb' unless Rails.root.join('app/views/layouts/printer.pdf.erb').exist?
template 'printer.rb', File.join('app/printers', class_path, "#{file_name}_printer.rb")
end
def create_custom_printer_views
passed_methods.each do |method_name|
@method_name = method_name
template 'template.pdf.erb', File.join('app/views/printers', class_path, "#{file_name}/#{method_name}.pdf.erb")
end
end
private
def file_name
@_file_name ||= super.gsub(/_printer/i, '')
end
def engine_mounted?
routes = Rails.root.join('config/routes.rb')
routes.exist? && routes.read.include?('Pixelpress::Engine')
end
end
end
end
|
nerdgeschoss/pixelpress
|
config/routes.rb
|
Pixelpress::Engine.routes.draw do
resources :printers, only: [:index] do
get ':id', to: 'printers#show'
end
end
|
nerdgeschoss/pixelpress
|
spec/pixelpress_spec.rb
|
<gh_stars>1-10
require 'spec_helper'
describe Pixelpress do
let(:renderer) { TestRenderer.new }
before(:each) do
ActionController::Base.view_paths << File.join(spec_root)
InvoicePrinter.default_renderer = renderer
end
class InvoicePrinter < Pixelpress::Base
def invoice
end
def file_name
'sasha'
end
end
class TestRenderer
attr_accessor :called
def render(html)
self.called = true
""
end
end
it 'selects the right template' do
expect(InvoicePrinter.invoice.html).to include 'Invoice'
end
it 'checks if the file name of pdf is correct' do
printer = InvoicePrinter.invoice.pdf
expect(printer.original_filename).to eq 'sasha'
end
it 'checks if it is calling weasyprinter when html is called' do
InvoicePrinter.invoice.html
expect(renderer.called).to be_falsy
end
fit 'checks if it is calling weasyprinter when pdf is called' do
InvoicePrinter.invoice.pdf
expect(renderer.called).to be_truthy
end
end
|
nerdgeschoss/pixelpress
|
lib/pixelpress/engine.rb
|
module Pixelpress
class Engine < ::Rails::Engine
isolate_namespace Pixelpress
end
end
|
nerdgeschoss/pixelpress
|
lib/pixelpress/instance_invocation.rb
|
<filename>lib/pixelpress/instance_invocation.rb
module Pixelpress
module InstanceInvocation
def method_missing(m, *args, &block)
return super unless respond_to_missing?(m)
instance = new
instance.instance_variable_set :@template_name, m.to_s
instance.send(m, *args)
instance.document
end
def respond_to_missing?(m, include_private = false)
return true if new.methods.include?(m)
end
end
end
|
nerdgeschoss/pixelpress
|
lib/generators/pixelpress/printer/templates/application_printer.rb
|
class ApplicationPrinter < Pixelpress::Base
layout 'printer'
end
|
nerdgeschoss/pixelpress
|
lib/pixelpress/document.rb
|
<gh_stars>1-10
require_relative 'fake_file'
module Pixelpress
class Document
attr_reader :html
attr_reader :file_name
def initialize(html, renderer, options = {})
@html = html
@renderer = renderer
@file_name = options[:file_name]
end
def pdf
FakeFile.new pdf_data, original_filename: file_name
end
private
attr_accessor :renderer
def pdf_data
@pdf_data ||= renderer.render(html)
end
end
end
|
nerdgeschoss/pixelpress
|
lib/generators/rspec/printer_generator.rb
|
<reponame>nerdgeschoss/pixelpress
module Rspec
module Generators
class PrinterGenerator < ::Rails::Generators::NamedBase
source_root File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
argument :passed_methods, type: :array, default: [], required: false, banner: 'method_name1 method_name2 ...'
check_class_collision suffix: 'Printer'
def create_printer_spec
template 'printer_spec.rb', File.join('spec/printers', class_path, "#{file_name}_printer_spec.rb")
end
def create_printer_previews
template 'preview.rb', File.join('spec/printers/previews', class_path, "#{file_name}_preview.rb")
end
private
def file_name
@_file_name ||= super.gsub(/_printer/i, '')
end
end
end
end
|
myokoym/gominohi
|
lib/gominohi/sources.rb
|
# -*- coding: utf-8 -*-
module Gominohi
SOURCES = [
{
name: "chuo_1",
areas: [
"中央区 南4条西7丁目・8丁目(南4条通の南側のみ),札幌センター1",
"中央区 南5条~8条の西7丁目・8丁目(南7条西8丁目1024番地を除く),札幌センター1",
"中央区 南9条西4丁目~6丁目(南9条通の南側のみ),札幌センター1",
"中央区 南9条西7丁目~12丁目,札幌センター1",
"中央区 南10条~13条の西5丁目~12丁目,札幌センター1",
"中央区 南14条西5丁目,札幌センター1",
"中央区 南14条西6丁目~12丁目(行啓通の北側のみ),札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["金"],
:paper => [],
:pet => ["火"],
},
special_day: "wednesday",
},
{
name: "chuo_2",
areas: [
"中央区 南14条西6丁目~12丁目(行啓通の南側のみ),札幌センター1",
"中央区 南15条西4丁目~12丁目,札幌センター1",
"中央区 南16条西1丁目~12丁目,札幌センター1",
"中央区 南17条西4丁目~15丁目,札幌センター1",
"中央区 南17条西16・17丁目(南17条通の南側のみ),札幌センター1",
"中央区 南18条~30条の西○丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["金"],
},
special_day: "tuesday",
},
{
name: "chuo_3",
areas: [
"中央区 南3条西11丁目・12丁目(南3条通の南側のみ),札幌センター1",
"中央区 南4条西9丁目・10丁目(南4条通の南側のみ),札幌センター1",
"中央区 南4条西11丁目~27丁目,札幌センター1",
"中央区 南5条~8条の西9丁目~27丁目,札幌センター1",
"中央区 南7条西8丁目1024番地,札幌センター1",
"中央区 南9条~16条の西13丁目~23丁目,札幌センター1",
"中央区 南17条西16丁目・17丁目(南17条通の北側のみ),札幌センター1",
"中央区 南17条西18丁目,札幌センター1",
"中央区 円山・双子山・界川・旭ヶ丘・伏見,札幌センター1",
"中央区 円山西町(9丁目5番、6番のみ),札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["火"],
:paper => [],
:pet => ["水"],
},
special_day: "friday",
},
{
name: "chuo_4",
areas: [
"中央区 北1条西10丁目~19丁目(北1条通の北側のみ),札幌センター1",
"中央区 北2条西8丁目~19丁目,札幌センター1",
"中央区 北3条・4条の西8丁目~20丁目,札幌センター1",
"中央区 北5条~11条の西9丁目~20丁目,札幌センター1",
"中央区 北12条~14条の西15丁目~19丁目,札幌センター1",
"中央区 北15条~22条の西○丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["木"],
},
special_day: "monday",
},
{
name: "chuo_5",
areas: [
"中央区 大通西20丁目~28丁目,札幌センター1",
"中央区 南1条~3条の西20丁目~28丁目,札幌センター1",
"中央区 北1条・2条の西20丁目~28丁目,札幌センター1",
"中央区 北3条~11条の西21丁目~30丁目,札幌センター1",
"中央区 北12条西20丁目~23丁目,札幌センター1",
"中央区 北14条西20丁目,札幌センター1",
"中央区 宮の森・宮ヶ丘・盤渓,札幌センター1",
"中央区 円山西町(9丁目5番、6番を除く),札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["月"],
:paper => [],
:pet => ["水"],
},
special_day: "thursday",
},
{
name: "chuo_6",
areas: [
"中央区 大通西1丁目~19丁目,札幌センター1",
"中央区 大通東○丁目,札幌センター1",
"中央区 南○条東○丁目,札幌センター1",
"中央区 北○条東○丁目,札幌センター1",
"中央区 南1条・2条の西1丁目~19丁目,札幌センター1",
"中央区 南3条西1丁目~10丁目・13丁目~18丁目,札幌センター1",
"中央区 南3条西11丁目・12丁目(南3条通の北側のみ),札幌センター1",
"中央区 南4条西1丁目~6丁目,札幌センター1",
"中央区 南4条西7丁目~10丁目(南4条通の北側のみ),札幌センター1",
"中央区 南5条~8条の西1丁目~6丁目,札幌センター1",
"中央区 南9条西1丁目~3丁目,札幌センター1",
"中央区 南9条西4丁目~6丁目(南9条通の北側のみ),札幌センター1",
"中央区 南10条~15条の西1丁目~3丁目,札幌センター1",
"中央区 北1条西1丁目~9丁目,札幌センター1",
"中央区 北1条西10丁目~19丁目(北1条通の南側のみ),札幌センター1",
"中央区 北2条~4条の西1丁目~7丁目,札幌センター1",
"中央区 北5条西1丁目~8丁目,札幌センター1",
"中央区 中島公園,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["木"],
:paper => [],
:pet => ["月"],
},
special_day: "wednesday",
},
{
name: "atsubetsu_1",
areas: [
"厚別区 厚別西○条○丁目、○番地,札幌センター1",
"厚別区 厚別北○条○丁目,札幌センター1",
"厚別区 厚別町山本○番地,札幌センター1",
"厚別区 厚別町小野幌○番地(JR函館本線の北側),札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["火"],
:paper => [],
:pet => ["水"],
},
special_day: "friday",
},
{
name: "atsubetsu_2",
areas: [
"厚別区 厚別中央1条1丁目~4丁目、7丁目,札幌センター1",
"厚別区 厚別中央2条~5条の○丁目,札幌センター1",
"厚別区 青葉町11丁目・12丁目、14丁目~16丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["火"],
:paper => [],
:pet => ["金"],
},
special_day: "wednesday",
},
{
name: "atsubetsu_3",
areas: [
"厚別区 厚別南○丁目,札幌センター1",
"厚別区 上野幌○条○丁目,札幌センター1",
"厚別区 厚別町上野幌○番地,札幌センター1",
"厚別区 大谷地西○丁目、東○丁目,札幌センター1",
"厚別区 青葉町1丁目~10丁目、13丁目,札幌センター1",
"厚別区 厚別中央1条5丁目・6丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["金"],
:paper => [],
:pet => ["火"],
},
special_day: "wednesday",
},
{
name: "atsubetsu_4",
areas: [
"厚別区 厚別東○条○丁目,札幌センター1",
"厚別区 厚別町下野幌○番地,札幌センター1",
"厚別区 もみじ台東・西・南・北の○丁目,札幌センター1",
"厚別区 厚別町小野幌○番地(JR函館本線の南側),札幌センター1",
"厚別区 下野幌テクノパーク○丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["金"],
},
special_day: "tuesday",
},
{
name: "shiroishi_1",
areas: [
"白石区 中央○条○丁目,札幌センター1",
"白石区 本通1丁目~14丁目(南北),札幌センター1",
"白石区 平和通1丁目~14丁目(南北),札幌センター1",
"白石区 本郷通1丁目~13丁目(南北),札幌センター1",
"白石区 南郷通1丁目~14丁目(南北),札幌センター1",
"白石区 栄通1丁目~14丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["月"],
:paper => [],
:pet => ["木"],
},
special_day: "wednesday",
},
{
name: "shiroishi_2",
areas: [
"白石区 北郷○条○丁目、○番地,札幌センター1",
"白石区 川北○条○丁目、○番地,札幌センター1",
"白石区 川下○条○丁目、○番地,札幌センター1",
"白石区 菊水元町○条○丁目,札幌センター1",
"白石区 東米里○番地,札幌センター1",
"白石区 米里○条○丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["木"],
:paper => [],
:pet => ["水"],
},
special_day: "monday",
},
{
name: "shiroishi_3",
areas: [
"白石区 東札幌○条○丁目,札幌センター1",
"白石区 菊水○条○丁目,札幌センター1",
"白石区 菊水上町○条○丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["月"],
},
special_day: "thursday",
},
{
name: "shiroishi_4",
areas: [
"白石区 本通15丁目~21丁目(南北),札幌センター1",
"白石区 平和通15丁目~17丁目(南北),札幌センター1",
"白石区 南郷通15丁目~21丁目(南北),札幌センター1",
"白石区 栄通15丁目~21丁目,札幌センター1",
"白石区 流通センター1丁目~7丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["金"],
:paper => [],
:pet => ["火"],
},
special_day: "wednesday",
},
{
name: "teine_1",
areas: [
"手稲区 西宮の沢○条○丁目,札幌センター1",
"手稲区 富丘○条○丁目,札幌センター1",
"手稲区 手稲本町○条○丁目,札幌センター1",
"手稲区 手稲本町○番地,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["月"],
},
special_day: "thursday",
},
{
name: "teine_2",
areas: [
"手稲区 前田○条○丁目,札幌センター1",
"手稲区 曙○条○丁目(曙12条2丁目・曙7条3丁目(明日風側)を除く),札幌センター1",
"手稲区 新発寒○条○丁目,札幌センター1",
"手稲区 手稲前田○番地,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["木"],
:paper => [],
:pet => ["水"],
},
special_day: "monday",
},
{
name: "teine_3",
areas: [
"手稲区 稲穂○条○丁目,札幌センター1",
"手稲区 金山○条○丁目,札幌センター1",
"手稲区 手稲金山○番地,札幌センター1",
"手稲区 星置○条○丁目,札幌センター1",
"手稲区 星置南○丁目,札幌センター1",
"手稲区 手稲山口○番地,札幌センター1",
"手稲区 明日風○丁目,札幌センター1",
"手稲区 曙12条2丁目・曙7条3丁目(明日風側),札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["木"],
:paper => [],
:pet => ["月"],
},
special_day: "wednesday",
},
{
name: "kiyota_1",
areas: [
"清田区 北野○条○丁目,札幌センター1",
"清田区 清田○条○丁目、○番地,札幌センター1",
"清田区 真栄○条○丁目、○番地,札幌センター1",
"清田区 有明○番地,札幌センター1",
"清田区 美しが丘1条~3条の1丁目・2丁目,札幌センター1",
"清田区 美しが丘3条3丁目1番・2番,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["火"],
:paper => [],
:pet => ["金"],
},
special_day: "wednesday",
},
{
name: "kiyota_2",
areas: [
"清田区 平岡○条○丁目,札幌センター1",
"清田区 平岡公園東○丁目,札幌センター1",
"清田区 里塚○条○丁目、○番地,札幌センター1",
"清田区 里塚緑ヶ丘○丁目,札幌センター1",
"清田区 美しが丘1条~3条の3丁目~10丁目(美しが丘3条3丁目1番・2番を除く),札幌センター1",
"清田区 美しが丘4条・5条の○丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["火"],
},
special_day: "friday",
},
{
name: "nishi_1",
areas: [
"西区 琴似○条○丁目,札幌センター1",
"西区 二十四軒○条○丁目,札幌センター1",
"西区 発寒○条○丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["火"],
:paper => [],
:pet => ["水"],
},
special_day: "friday",
},
{
name: "nishi_2",
areas: [
"西区 山の手○条○丁目、○番地,札幌センター1",
"西区 西野6条~14条の○丁目,札幌センター1",
"西区 西野○番地(西野290番地を除く),札幌センター1",
"西区 平和○条○丁目、○番地,札幌センター1",
"西区 福井○丁目、○番地,札幌センター1",
"西区 小別沢○番地,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["金"],
},
special_day: "tuesday",
},
{
name: "nishi_3",
areas: [
"西区 西野1条~5条の○丁目(西野290番地),札幌センター1",
"西区 西町北○丁目、南○丁目,札幌センター1",
"西区 宮の沢○条○丁目、○番地,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["金"],
:paper => [],
:pet => ["火"],
},
special_day: "wednesday",
},
{
name: "nishi_4",
areas: [
"西区 八軒○条西○丁目,札幌センター1",
"西区 八軒○条東○丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["月"],
:paper => [],
:pet => ["木"],
},
special_day: "wednesday",
},
{
name: "higashi_1",
areas: [
"東区 北34条~51条の東1丁目~15丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["金"],
},
special_day: "tuesday",
},
{
name: "higashi_2",
areas: [
"東区 北34条~49条の東16丁目~30丁目,札幌センター1",
"東区 伏古11条~14条の1丁目~5丁目,札幌センター1",
"東区 丘珠町○番地,札幌センター1",
"東区 栄町○番地,札幌センター1",
"東区 北丘珠○条○丁目,札幌センター1",
"東区 東苗穂町○番地,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["金"],
:paper => [],
:pet => ["火"],
},
special_day: "wednesday",
},
{
name: "higashi_3",
areas: [
"東区 伏古1条~10条の1丁目~5丁目,札幌センター1",
"東区 東苗穂○条○丁目,札幌センター1",
"東区 東雁来○条○丁目,札幌センター1",
"東区 東雁来町○番地,札幌センター1",
"東区 中沼○条○丁目,札幌センター1",
"東区 中沼町○番地,札幌センター1",
"東区 中沼西○条○丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["火"],
:paper => [],
:pet => ["水"],
},
special_day: "friday",
},
{
name: "higashi_4",
areas: [
"東区 北5条~33条の東1丁目~7丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["木"],
},
special_day: "monday",
},
{
name: "higashi_5",
areas: [
"東区 北15条~33条の東8丁目~15丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["木"],
:paper => [],
:pet => ["月"],
},
special_day: "wednesday",
},
{
name: "higashi_6",
areas: [
"東区 北4条~14条の東8丁目~20丁目,札幌センター1",
"東区 北15条~33条の東16丁目~23丁目,札幌センター1",
"東区 苗穂町○丁目,札幌センター1",
"東区 本町○条○丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["月"],
:paper => [],
:pet => ["水"],
},
special_day: "thursday",
},
{
name: "kita_1",
areas: [
"北区 北6条~31条の西○丁目,札幌センター1",
"北区 北32条西2丁目~12丁目,札幌センター1",
"北区 北33条西2丁目~8丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["火"],
:paper => [],
:pet => ["金"],
},
special_day: "wednesday",
},
{
name: "kita_2",
areas: [
"北区 新川○条○丁目、○番地,札幌センター1",
"北区 新川西○条○丁目,札幌センター1",
"北区 新琴似1条~3条の12丁目・13丁目,札幌センター1",
"北区 新琴似4条~10条の12丁目~17丁目,札幌センター1",
"北区 新琴似11条・12条の14丁目~17丁目,札幌センター1",
"北区 新琴似町○番地,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["金"],
:paper => [],
:pet => ["水"],
},
special_day: "tuesday",
},
{
name: "kita_3",
areas: [
"北区 新琴似1条~10条の1丁目~11丁目,札幌センター1",
"北区 新琴似11条・12条の1丁目~13丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["火"],
},
special_day: "friday",
},
{
name: "kita_4",
areas: [
"北区 屯田○条○丁目,札幌センター1",
"北区 屯田町○番地,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["木"],
},
special_day: "monday",
},
{
name: "kita_5",
areas: [
"北区 麻生町○丁目,札幌センター1",
"北区 北32条西13丁目,札幌センター1",
"北区 北33条西9丁目~12丁目,札幌センター1",
"北区 北34条~40条の西○丁目,札幌センター1",
"北区 太平○条○丁目,札幌センター1",
"北区 篠路町太平○番地,札幌センター1",
"北区 百合が原○丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["木"],
:paper => [],
:pet => ["月"],
},
special_day: "wednesday",
},
{
name: "kita_6",
areas: [
"北区 篠路○条○丁目,札幌センター1",
"北区 篠路町篠路○番地,札幌センター1",
"北区 篠路町福移○番地,札幌センター1",
"北区 篠路町上篠路○番地,札幌センター1",
"北区 西茨戸○条○丁目、○番地,札幌センター1",
"北区 東茨戸○条○丁目、○番地,札幌センター1",
"北区 拓北○条○丁目,札幌センター1",
"北区 篠路町拓北○番地,札幌センター1",
"北区 あいの里○条○丁目,札幌センター1",
"北区 南あいの里○丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["月"],
:paper => [],
:pet => ["水"],
},
special_day: "thursday",
},
{
name: "minami_1",
areas: [
"南区 澄川2条4丁目(12番~14番),札幌センター1",
"南区 澄川2条5丁目,札幌センター1",
"南区 澄川3条4丁目(7番),札幌センター1",
"南区 澄川3条5丁目・6丁目,札幌センター1",
"南区 澄川4条4丁目(1番18号~27号、2番~11番),札幌センター1",
"南区 澄川4条5丁目~12丁目,札幌センター1",
"南区 澄川5条4丁目(1番・7番~9番),札幌センター1",
"南区 澄川5条5丁目(1番~9番),札幌センター1",
"南区 澄川5条6丁目(1番~8番),札幌センター1",
"南区 澄川5条7丁目~13丁目,札幌センター1",
"南区 澄川6条7丁目~13丁目,札幌センター1",
"南区 澄川○番地,札幌センター1",
"南区 真駒内柏丘・東町・幸町・泉町・南町の○丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["火"],
:paper => [],
:pet => ["水"],
},
special_day: "friday",
},
{
name: "minami_2",
areas: [
"南区 石山○条○丁目、○番地(石山1条1丁目12-6パレス藻南公園を除く),札幌センター1",
"南区 石山東○丁目,札幌センター1",
"南区 常盤○条○丁目、○番地,札幌センター1",
"南区 滝野○番地,札幌センター1",
"南区 真駒内○番地(自衛隊真駒内駐屯地を除く),札幌センター1",
"南区 芸術の森○丁目,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["金"],
},
special_day: "tuesday",
},
{
name: "minami_3",
areas: [
"南区 藤野○条○丁目、○番地,札幌センター1",
"南区 白川○番地,札幌センター1",
"南区 簾舞○条○丁目、○番地,札幌センター1",
"南区 砥山○番地,札幌センター1",
"南区 豊滝○番地,札幌センター1",
"南区 硬石山○番地,札幌センター1",
"南区 小金湯○番地,札幌センター1",
"南区 定山渓温泉西・東の○丁目,札幌センター1",
"南区 定山渓○番地,札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["金"],
:paper => [],
:pet => ["火"],
},
special_day: "wednesday",
},
{
name: "minami_4",
areas: [
"南区 澄川1条1丁目~4丁目,札幌センター1",
"南区 澄川2条1丁目~3丁目・4丁目(1番~11番),札幌センター1",
"南区 澄川3条1丁目~3丁目・4丁目(1番~6番),札幌センター1",
"南区 澄川4条1丁目~3丁目・4丁目(1番1号~17号),札幌センター1",
"南区 澄川5条3丁目・4丁目(2番~6番),札幌センター1",
"南区 澄川5条5丁目(10番~19番),札幌センター1",
"南区 澄川5条6丁目(9番~14番),札幌センター1",
"南区 澄川6条3丁目~6丁目,札幌センター1",
"南区 真駒内本町・曙町・上町・緑町の○丁目,札幌センター1",
"南区 真駒内○番地(自衛隊真駒内駐屯地のみ),札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["木"],
:paper => [],
:pet => ["水"],
},
special_day: "monday",
},
{
name: "minami_5",
areas: [
"南区 南30条~39条の西○丁目,札幌センター1",
"南区 藻岩下○丁目、○番地,札幌センター1",
"南区 川沿1条~6条の○丁目,札幌センター1",
"南区 北ノ沢○丁目、○番地,札幌センター1",
"南区 中ノ沢○丁目、○番地,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["月"],
:paper => [],
:pet => ["水"],
},
special_day: "thursday",
},
{
name: "minami_6",
areas: [
"南区 南沢○条○丁目、○番地(南沢1条3丁目1番(南沢やまどり公園)、20番、21番を除く),札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["月"],
:paper => [],
:pet => ["木"],
},
special_day: "wednesday",
},
{
name: "minami_7",
areas: [
"南区 川沿7条~18条の○丁目,札幌センター1",
"南区 南沢1条3丁目1番(南沢やまどり公園),札幌センター1",
"南区 南沢1条3丁目20番、21番,札幌センター1",
"南区 石山1条1丁目(12番6号パレス藻南公園のみ),札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["月"],
},
special_day: "thursday",
},
{
name: "toyohira_1",
areas: [
"豊平区 豊平○条○丁目,札幌センター1",
"豊平区 旭町○丁目,札幌センター1",
"豊平区 水車町○丁目,札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["水"],
:paper => [],
:pet => ["木"],
},
special_day: "monday",
},
{
name: "toyohira_2",
areas: [
"豊平区 中の島○条○丁目,札幌センター1",
"豊平区 平岸○条○丁目,札幌センター1",
"豊平区 美園○条○丁目,札幌センター1",
"豊平区 月寒西1条2丁目1番(望月寒川沿いのみ),札幌センター1",
"豊平区 月寒西2条4丁目1番,札幌センター1",
"豊平区 月寒中央通1丁目1番(望月寒川沿いのみ),札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["木"],
:paper => [],
:pet => ["月"],
},
special_day: "wednesday",
},
{
name: "toyohira_3",
areas: [
"豊平区 西岡○条○丁目、○番地,札幌センター1",
"豊平区 福住○条○丁目,札幌センター1",
"豊平区 羊ヶ丘(森林総合研究所公務員宿舎のみ),札幌センター1",
],
types: {
:burn => ["火", "金"],
:leaf => [],
:not_burn => [],
:plastic => ["月"],
:paper => [],
:pet => ["水"],
},
special_day: "thursday",
},
{
name: "toyohira_4",
areas: [
"豊平区 月寒東○条○丁目,札幌センター1",
"豊平区 月寒西○条○丁目(月寒西1条2丁目1番の望月寒川沿い・月寒西2条4丁目1番を除く),札幌センター1",
"豊平区 月寒中央通○丁目(月寒中央通1丁目1番の望月寒川沿いを除く),札幌センター1",
"豊平区 羊ヶ丘(北海道農業研修センター宿舎・動物衛生研究所宿舎のみ),札幌センター1",
],
types: {
:burn => ["月", "木"],
:leaf => [],
:not_burn => [],
:plastic => ["金"],
:paper => [],
:pet => ["水"],
},
special_day: "tuesday",
},
]
end
|
myokoym/gominohi
|
lib/gominohi.rb
|
require "gominohi/generator"
require "gominohi/sources"
require "gominohi/version"
|
myokoym/gominohi
|
lib/gominohi/command.rb
|
# -*- coding: utf-8 -*-
require "thor"
require "gominohi/generator"
require "gominohi/sources"
require "gominohi/version"
module Gominohi
class Command < Thor
map "-v" => :version
map "-g" => :generate
desc "version", "Show version number."
def version
puts Gominohi::VERSION
end
desc "generate PLACE BEGIN END [1-4]", "Generate garbage days."
def generate(place, begin_date, end_date, order=1)
case order.to_i
when 1
special_order = [:paper, :not_burn, :paper, :leaf]
when 2
special_order = [:leaf, :paper, :not_burn, :paper]
when 3
special_order = [:paper, :leaf, :paper, :not_burn]
when 4
special_order = [:not_burn, :paper, :leaf, :paper]
else
raise ArgumentError, "特殊曜日の順序が不正です。"
end
puts Generator.__send__(place, begin_date, end_date, special_order)
end
end
end
|
myokoym/gominohi
|
lib/gominohi/generator.rb
|
# -*- coding: utf-8 -*-
require "date"
require "gominohi/sources"
module Gominohi
class Generator
class << self
SOURCES.each do |source|
define_method(source[:name]) do |begin_date = source[:begin_date],
end_date = source[:end_date],
special_order = source[:special_order]|
days = days(begin_date,
end_date,
Marshal.load(Marshal.dump(source[:types])),
source[:special_day],
special_order)
source[:areas].collect do |area|
"#{area},#{days}"
end
end
end
private
def days(begin_date, end_date, types, special_day, special_order)
special_dates = []
current_date = Date.parse(begin_date)
end_date = Date.parse(end_date)
current_special_date = nil
7.times do
if current_date.send("#{special_day}?")
current_special_date = current_date
break
end
current_date += 1
end
raise "ぬるぽ" unless current_special_date
loop do
break unless current_special_date < end_date
special_dates << current_special_date
current_special_date += 7
end
special_dates.reject! do |date|
# TODO: 年末年始は要確認
/\A(1230|010[1-5])\z/ =~ date.strftime("%m%d")
end
special_dates.each_slice(special_order.size) do |dates|
dates.each_with_index do |date, i|
type = special_order[i]
next if type == :leaf and leaf_is_stopped?(date)
types[type] << date.strftime("%Y%m%d")
end
end
types.values.collect { |group|
group.join(" ")
}.join(",")
end
def leaf_is_stopped?(date)
(1..4).include?(date.month) or
(date.month == 12 and date.day > 10)
end
end
end
end
|
myokoym/gominohi
|
test/test-generator.rb
|
require "gominohi/generator"
class GominohiGeneratorTest < Test::Unit::TestCase
def test_leaf_in_december
expected = [
"白石区 東札幌○条○丁目,札幌センター1,火 金,20141204,,水,,月",
"白石区 菊水○条○丁目,札幌センター1,火 金,20141204,,水,,月",
"白石区 菊水上町○条○丁目,札幌センター1,火 金,20141204,,水,,月",
]
special_order = [:leaf]
assert_equal(expected,
Gominohi::Generator.shiroishi_3("2014-12-01",
"2014-12-31",
special_order))
end
def test_shiroishi_1
expected = [
"白石区 中央○条○丁目,札幌センター1,火 金,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,月,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,木",
"白石区 本通1丁目~14丁目(南北),札幌センター1,火 金,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,月,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,木",
"白石区 平和通1丁目~14丁目(南北),札幌センター1,火 金,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,月,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,木",
"白石区 本郷通1丁目~13丁目(南北),札幌センター1,火 金,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,月,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,木",
"白石区 南郷通1丁目~14丁目(南北),札幌センター1,火 金,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,月,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,木",
"白石区 栄通1丁目~14丁目,札幌センター1,火 金,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,月,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,木",
]
special_order = [:paper, :not_burn, :paper, :leaf]
assert_equal(expected,
Gominohi::Generator.shiroishi_1("2014-02-26",
"2014-09-30",
special_order))
end
def test_shiroishi_2
expected = [
"白石区 北郷○条○丁目、○番地,札幌センター1,火 金,20140512 20140609 20140707 20140804 20140901 20140929,20140303 20140331 20140428 20140526 20140623 20140721 20140818 20140915,木,20140224 20140310 20140324 20140407 20140421 20140505 20140519 20140602 20140616 20140630 20140714 20140728 20140811 20140825 20140908 20140922,水",
"白石区 川北○条○丁目、○番地,札幌センター1,火 金,20140512 20140609 20140707 20140804 20140901 20140929,20140303 20140331 20140428 20140526 20140623 20140721 20140818 20140915,木,20140224 20140310 20140324 20140407 20140421 20140505 20140519 20140602 20140616 20140630 20140714 20140728 20140811 20140825 20140908 20140922,水",
"白石区 川下○条○丁目、○番地,札幌センター1,火 金,20140512 20140609 20140707 20140804 20140901 20140929,20140303 20140331 20140428 20140526 20140623 20140721 20140818 20140915,木,20140224 20140310 20140324 20140407 20140421 20140505 20140519 20140602 20140616 20140630 20140714 20140728 20140811 20140825 20140908 20140922,水",
"白石区 菊水元町○条○丁目,札幌センター1,火 金,20140512 20140609 20140707 20140804 20140901 20140929,20140303 20140331 20140428 20140526 20140623 20140721 20140818 20140915,木,20140224 20140310 20140324 20140407 20140421 20140505 20140519 20140602 20140616 20140630 20140714 20140728 20140811 20140825 20140908 20140922,水",
"白石区 東米里○番地,札幌センター1,火 金,20140512 20140609 20140707 20140804 20140901 20140929,20140303 20140331 20140428 20140526 20140623 20140721 20140818 20140915,木,20140224 20140310 20140324 20140407 20140421 20140505 20140519 20140602 20140616 20140630 20140714 20140728 20140811 20140825 20140908 20140922,水",
"白石区 米里○条○丁目,札幌センター1,火 金,20140512 20140609 20140707 20140804 20140901 20140929,20140303 20140331 20140428 20140526 20140623 20140721 20140818 20140915,木,20140224 20140310 20140324 20140407 20140421 20140505 20140519 20140602 20140616 20140630 20140714 20140728 20140811 20140825 20140908 20140922,水",
]
special_order = [:paper, :not_burn, :paper, :leaf]
assert_equal(expected,
Gominohi::Generator.shiroishi_2("2014-02-24",
"2014-09-30",
special_order))
end
def test_shiroishi_3
expected = [
"白石区 東札幌○条○丁目,札幌センター1,火 金,20140515 20140612 20140710 20140807 20140904,20140306 20140403 20140501 20140529 20140626 20140724 20140821 20140918,水,20140227 20140313 20140327 20140410 20140424 20140508 20140522 20140605 20140619 20140703 20140717 20140731 20140814 20140828 20140911 20140925,月",
"白石区 菊水○条○丁目,札幌センター1,火 金,20140515 20140612 20140710 20140807 20140904,20140306 20140403 20140501 20140529 20140626 20140724 20140821 20140918,水,20140227 20140313 20140327 20140410 20140424 20140508 20140522 20140605 20140619 20140703 20140717 20140731 20140814 20140828 20140911 20140925,月",
"白石区 菊水上町○条○丁目,札幌センター1,火 金,20140515 20140612 20140710 20140807 20140904,20140306 20140403 20140501 20140529 20140626 20140724 20140821 20140918,水,20140227 20140313 20140327 20140410 20140424 20140508 20140522 20140605 20140619 20140703 20140717 20140731 20140814 20140828 20140911 20140925,月",
]
special_order = [:paper, :not_burn, :paper, :leaf]
assert_equal(expected,
Gominohi::Generator.shiroishi_3("2014-02-27",
"2014-09-30",
special_order))
end
def test_shiroishi_4
expected = [
"白石区 本通15丁目~21丁目(南北),札幌センター1,月 木,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,金,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,火",
"白石区 平和通15丁目~17丁目(南北),札幌センター1,月 木,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,金,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,火",
"白石区 南郷通15丁目~21丁目(南北),札幌センター1,月 木,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,金,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,火",
"白石区 栄通15丁目~21丁目,札幌センター1,月 木,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,金,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,火",
"白石区 流通センター1丁目~7丁目,札幌センター1,月 木,20140514 20140611 20140709 20140806 20140903,20140305 20140402 20140430 20140528 20140625 20140723 20140820 20140917,金,20140226 20140312 20140326 20140409 20140423 20140507 20140521 20140604 20140618 20140702 20140716 20140730 20140813 20140827 20140910 20140924,火",
]
special_order = [:paper, :not_burn, :paper, :leaf]
assert_equal(expected,
Gominohi::Generator.shiroishi_4("2014-02-26",
"2014-09-30",
special_order))
end
end
|
Flowspace-Team/omniauth-amazon-sp-api
|
lib/omniauth-amazon-sp-api.rb
|
<filename>lib/omniauth-amazon-sp-api.rb
require 'omniauth/amazon-sp-api'
|
Flowspace-Team/omniauth-amazon-sp-api
|
lib/omniauth/amazon-sp-api.rb
|
require "omniauth/amazon-sp-api/version"
require "omniauth/strategies/amazon-sp-api"
|
ablignaut/PagedList
|
rakefile.rb
|
<filename>rakefile.rb
require 'albacore' # >= 0.2.7
require 'fileutils'
load './version.rb'
task :default => [:build]
assemblyinfo :generate_pagedlist_assemblyinfo do |asm|
asm.version = PAGEDLIST_VERSION
asm.company_name = "<NAME>"
asm.product_name = "PagedList"
asm.title = "PagedList"
asm.description = "PagedList makes it easier for .Net developers to write paging code. It allows you to take any IEnumerable(T) and by specifying the page size and desired page index, select only a subset of that list. PagedList also provides properties that are useful when building UI paging controls."
asm.copyright = "MIT License"
asm.custom_attributes \
:CLSCompliant => true,
:ComVisible => false,
:Guid => "1d709432-45fa-4475-a403-b2310a47d0a6",
:AllowPartiallyTrustedCallers => nil,
:AssemblyFileVersion => PAGEDLIST_VERSION,
:AssemblyConfiguration => '',
:AssemblyTrademark => '',
:AssemblyCulture => ''
asm.namespaces "System", "System.Security"
asm.output_file = "src/PagedList/Properties/AssemblyInfo.cs"
end
assemblyinfo :generate_pagedlistmvc_assemblyinfo do |asm|
asm.version = PAGEDLIST_MVC_VERSION
asm.company_name = "<NAME>"
asm.product_name = "PagedList.Mvc"
asm.title = "PagedList.Mvc"
asm.description = "Asp.Net MVC HtmlHelper method for generating paging control for use with PagedList library."
asm.copyright = "MIT License"
asm.custom_attributes \
:CLSCompliant => true,
:ComVisible => false,
:Guid => "eb684fee-2094-4833-ae61-f9bfcab34abd",
:AllowPartiallyTrustedCallers => nil,
:AssemblyFileVersion => PAGEDLIST_MVC_VERSION,
:AssemblyConfiguration => '',
:AssemblyTrademark => '',
:AssemblyCulture => ''
asm.namespaces "System", "System.Security"
asm.output_file = "src/PagedList.Mvc/Properties/AssemblyInfo.cs"
end
nuspec :generate_pagedlist_nuspec do |nuspec|
nuspec.title = "$id$"
nuspec.id = "$id$"
nuspec.version = "$version$"
nuspec.authors = "$author$"
nuspec.owners = "TroyGoode"
nuspec.description = "$description$"
nuspec.language = "en-US"
nuspec.licenseUrl = "http://www.opensource.org/licenses/mit-license.php"
nuspec.projectUrl = "http://github.com/TroyGoode/PagedList"
nuspec.tags = "paging pager page infinitescroll ajax mvc"
nuspec.output_file = "src/PagedList/PagedList.nuspec"
end
nuspec :generate_pagedlistmvc_nuspec do |nuspec|
nuspec.title = "$id$"
nuspec.id = "$id$"
nuspec.version = "$version$"
nuspec.authors = "$author$"
nuspec.owners = "TroyGoode"
nuspec.description = "$description$"
nuspec.language = "en-US"
nuspec.licenseUrl = "http://www.opensource.org/licenses/mit-license.php"
nuspec.projectUrl = "http://github.com/TroyGoode/PagedList"
nuspec.tags = "paging pager page infinitescroll ajax mvc"
nuspec.dependency "PagedList", PAGEDLIST_VERSION
nuspec.file "Content\\**\\*.*", "Content"
nuspec.output_file = "src/PagedList.Mvc/PagedList.Mvc.nuspec"
end
msbuild :build => [:generate_pagedlist_assemblyinfo, :generate_pagedlistmvc_assemblyinfo, :generate_pagedlist_nuspec, :generate_pagedlistmvc_nuspec] do |msb|
msb.properties :configuration => :Debug
msb.targets :Clean, :Rebuild
msb.solution = "src/PagedList.sln"
end
xunit :test => :build do |xunit|
xunit.command = "src/PagedList.Tests/Dependencies/xunit-1.8/xunit.console.clr4.exe"
xunit.assembly = "src/PagedList.Tests/bin/debug/PagedList.Tests.dll"
end
msbuild :release => :test do |msb|
msb.properties :configuration => :Release
msb.targets :Clean, :Rebuild
msb.solution = "src/PagedList.sln"
end
nugetpack :package_pagedlist => :release do |nuget|
nuget.nuspec = './src/PagedList/PagedList.csproj -Prop Configuration=Release'
nuget.output = './packages/'
end
#HACK: remove once http://nuget.codeplex.com/workitem/1349 is fixed
task :prepare_package_pagedlistmvc => :release do
content_directory = './src/PagedList.Mvc.Example/Content/'
script_directory = './src/PagedList.Mvc.Example/Scripts/PagedList/'
content_directory_out = './src/PagedList.Mvc/Content/Content/'
script_directory_out = './src/PagedList.Mvc/Content/Scripts/PagedList/'
FileUtils.mkdir_p content_directory_out
FileUtils.mkdir_p script_directory_out
FileUtils.cp content_directory + 'PagedList.css', content_directory_out + 'PagedList.css'
FileUtils.cp script_directory + 'PagedList.Mvc.js', script_directory_out + 'PagedList.Mvc.js'
FileUtils.cp script_directory + 'PagedList.Mvc.Template.html', script_directory_out + 'PagedList.Mvc.Template.html'
end
nugetpack :package_pagedlistmvc => :prepare_package_pagedlistmvc do |nuget|
nuget.nuspec = './src/PagedList.Mvc/PagedList.Mvc.csproj -Prop Configuration=Release'
nuget.output = './packages/'
end
task :package => [:package_pagedlist, :package_pagedlistmvc] do
end
nugetpush :push_pagedlist => :package_pagedlist do |nuget|
ver = String.new(PAGEDLIST_VERSION)
ver.slice!(/(\.0)*$/)
nuget.package = "./packages/PagedList.#{ver}.nupkg"
end
nugetpush :push_pagedlistmvc => :package_pagedlistmvc do |nuget|
ver = String.new(PAGEDLIST_MVC_VERSION)
ver.slice!(/(\.0)*$/)
nuget.package = "./packages/PagedList.Mvc.#{ver}.nupkg"
end
task :push => [:push_pagedlist, :push_pagedlistmvc] do
end
|
ablignaut/PagedList
|
version.rb
|
PAGEDLIST_VERSION = '1.14'
PAGEDLIST_MVC_VERSION = '3.14'
|
ykominami/genx
|
lib/genx/plugin.rb
|
module Genx
class Plugin
def initialize(args)
end
def run
end
end
end
|
ykominami/genx
|
lib/genx/util.rb
|
<gh_stars>0
module Genx
# Utility class
class Util
class << self
def get_file_content(file_path)
get_file_content_lines(file_path).join("\n")
end
def get_file_content_lines(file_path)
File.readlines(file_path).select{ |l| l !~ /^(\s*)#/ }.map(&:chomp)
end
end
# Returns the current time in milliseconds
end
end
|
ykominami/genx
|
lib/genx/varsplugin.rb
|
module Genx
class VarsPlugin < Plugin
def initialize(argv1)
@argvx1 = argv1
@yaml_file = @argvx1[1]
@templ_file = @argvx1[2]
@templ_vars_file = @argvx1[3]
templ_pn = Pathname.new(@templ_file)
@templ_content = Util.get_file_content(templ_pn)
templ_vars_pn = Pathname.new(@templ_vars_file)
@templ_vars_content = Util.get_file_content(templ_vars_pn)
yaml_pn = Pathname.new(@yaml_file)
yaml_content = Util.get_file_content(yaml_pn)
@yaml_hs = YAML.load(yaml_content)
end
def run
ret_code = 0
eruby_class = Erubis::Eruby.new(@templ_content)
eruby_vars = Erubis::Eruby.new(@templ_vars_content)
data_hs = {}
ary = @yaml_hs.map{
|classname, hs|
hs.map{ |group_id, hs2|
varnames, var_list = make_var_def(eruby_vars, hs2)
data_hs["classname"] = classname
data_hs["var_list"] = var_list.join("\n")
data_hs["varname_list"] = varnames.join(",")
eruby_class.result(data_hs)
}
}
[ret_code, ary]
end
def make_var_def(eruby, hs)
varnames = []
list = []
hs_vars = {}
if hs["vars"]
hs["vars"].each do |var_name, var_value|
hs_vars["var_name"] = var_name
hs_vars["var_value"] = var_value
varnames << var_name
list << eruby.result(hs_vars)
end
end
[varnames, list]
end
end
end
|
ykominami/genx
|
spec/genx_spec.rb
|
# frozen_string_literal: true
require 'spec_helper'
RSpec.describe Genx do
it "has a version number" do
expect(Genx::VERSION).not_to be nil
end
context "create instance" do
before(:all) do
home_dir = '/home/ykominami'
home_pn = Pathname.new(home_dir)
home_genx_pn =home_pn.join('.genx')
ary = ["data1.yml", "templ1.txt", "templ_vars.txt"].map{|x| home_genx_pn.join(x)}
@argv = ["vars"] + ary
@exit_success_code = 0
@exit_error_code = 1
end
let(:instance) { Genx::Genx.new(@argv) }
it "Genx" do
expect(instance).to_not eq(nil)
end
context "run" do
let(:ret) {instance.run}
it "" do
expect(ret).to eq(@exit_success_code)
end
end
let(:instance) { Genx::Plugin.new(@argv) }
it "Plugin" do
expect(instance).to_not eq(nil)
end
context "run" do
let(:ret) {instance.run}
it "" do
expect(ret).to eq(@exit_success_code)
end
end
let(:instance) { Genx::VarsPlugin.new(@argv) }
it "VarsPlugin" do
expect(instance).to_not eq(nil)
end
context "run" do
let(:ret) {instance.run}
it "" do
expect(ret).to eq(@exit_success_code)
end
end
=begin
context "run" do
p "spec 2"
let(:ret) {instance.run}
it "run" do
expect(ret).to eq(true)
end
end
=end
end
end
|
ykominami/genx
|
spec2/tea_spec.rb
|
class Tea
def flavor
'earl gray'
end
def temperature
250
end
end
RSpec.configure do |config|
config.example_status_persistence_file_path = 'spec/example.txt'
end
RSpec.describe Tea do
let(:tea) { Tea.new }
it 'tastes like Earl Gray' do
expect(tea.flavor).to eq('earl gray')
end
it 'is hot' do
expect(tea.temperature).to be > 200.0
end
end
|
ykominami/genx
|
lib/genx.rb
|
<reponame>ykominami/genx<filename>lib/genx.rb
# frozen_string_literal: true
require_relative "genx/version"
require_relative "genx/genx"
require_relative "genx/util"
require_relative "genx/plugin"
require_relative "genx/varsplugin"
module Genx
class Error < StandardError; end
# Your code goes here...
end
|
ykominami/genx
|
lib/genx/genx.rb
|
<filename>lib/genx/genx.rb
# frozen_string_literal: true
module Genx
require 'erubis'
require 'pathname'
require 'yaml'
class Genx
def initialize(argvx)
plugin_name = argvx[0]
module_name = "Genx"
plugin_classname = plugin_name.capitalize + 'Plugin'
plugin_classname_with_ns = [module_name , plugin_name.capitalize + 'Plugin'].join('::')
@plugin_klass = Object.const_get(plugin_classname_with_ns)
@plugin_object = @plugin_klass.new(argvx)
end
def run
ret , ary = @plugin_object.run
end
end
end
|
jschmid/UpdatePlistFromStrings-fastlane-plugin
|
lib/fastlane/plugin/updateplistfromstrings/actions/updateplistfromstrings_action.rb
|
<filename>lib/fastlane/plugin/updateplistfromstrings/actions/updateplistfromstrings_action.rb
module Fastlane
module Actions
class UpdateplistfromstringsAction < Action
def self.run(params)
input_file = params[:translations_source_file]
target_file = params[:info_plist_strings_target_file]
target_file_tmp = target_file + ".UpdateplistfromstringsAction.tmp"
managed_marker = params[:managed_value_marker]
key_map = params[:string_key_map]
use_key_for_empty_value = params[:use_source_key_for_empty_values]
set_in_plist = params[:set_values_in_info_plist]
plist_path = params[:plist_path]
omit_if_empty_value = params[:omit_if_value_empty]
raise "Must provide a value for :plist_path if :set_in_plist is true" if set_in_plist and plist_path == ""
# Preserve the non-managed lines:
non_managed_lines = []
if File.exist?(target_file)
non_managed_lines = File.readlines(target_file, encoding: 'bom|utf-8').map { |line| line.strip unless line =~ /#{managed_marker}/ }.compact
end
# Build the managed lines, and set Info.plist key/values.
managed_lines = []
managed_target_keys = []
open(input_file, encoding: 'bom|utf-8') do |f|
f.each_line do |line|
key_map.each do |target_key, source_key|
regex = /^"#{source_key}"\s*=\s*"(?<value>.*)"\s*;\s*$/
matches = line.match(regex)
next unless matches
next if omit_if_empty_value and matches['value'].empty?
quoted_source_key = %("#{source_key}")
target_line = line.sub(quoted_source_key, target_key).strip
if use_key_for_empty_value and matches['value'].empty?
value = source_key
target_line.sub!(/"";$/, quoted_source_key + ";")
else
value = matches['value']
end
target_line += " /* #{managed_marker} */"
managed_lines << target_line
managed_target_keys << target_key
if set_in_plist
UI.message "Setting in Info.plist: #{target_key} = #{value}"
Fastlane::Actions::SetInfoPlistValueAction.run(path: plist_path, key: target_key, value: value)
end
end
end
end
# Remove any non-managed lines that are now managed.
non_managed_lines = non_managed_lines.reject do |line|
managed_target_keys.find { |key| line.match(/^#{key}\s*=\s*".*"\s*;.*$/) }
end
IO.write(target_file_tmp, (non_managed_lines + managed_lines).join("\n") + "\n")
FileUtils.mv(target_file_tmp, target_file, force: true)
UI.message "#{managed_lines.length} managed translation values set in #{target_file}"
end
#####################################################
# @!group Documentation
#####################################################
def self.description
"Update InfoPlist.strings from translation file"
end
def self.details
"Add / update selected translations from a source Localizable.strings file to a InfoPlist.strings file"
end
def self.available_options
[
FastlaneCore::ConfigItem.new(key: :translations_source_file,
description: "Full path to translations file (used to extract the translation)"),
FastlaneCore::ConfigItem.new(key: :info_plist_strings_target_file,
description: "Full path to InfoPlist.strings file (which will have the translated values set)"),
FastlaneCore::ConfigItem.new(key: :string_key_map,
description: "A Hash of destination(InfoPlist.strings) keys => source(from translations_source_file) keys to use. If a translation for the source key exists in the source file, the translation will be added / updated in the target file",
is_string: false,
default_value: {}),
FastlaneCore::ConfigItem.new(key: :managed_value_marker,
description: "A string that will be embedded in a comment on each translation line of the target file, to indicate that it is a fastlane-managed item",
default_value: "fastlane_managed_value_marker"),
FastlaneCore::ConfigItem.new(key: :omit_if_value_empty,
description: "If true, and a key exists in the source file whose value is an empty string, do not add the values to the target file (and Info.plist, if :set_values_in_info_plist is true)",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :use_source_key_for_empty_values,
description: "If true, and a key exists in the source file whose value is an empty string, the source file key will be used instead of an empty string when writing to the target file",
is_string: false,
default_value: true),
FastlaneCore::ConfigItem.new(key: :set_values_in_info_plist,
description: "If true, set the corresponding values in Info.plist. If a fallback language has been specified by setting the app's CFBundleDevelopmentRegion, and it is certain that all translations are present for that language, this should be set to false",
is_string: false,
default_value: false),
FastlaneCore::ConfigItem.new(key: :plist_path,
description: "Path to Info.plist file",
default_value: "")
]
end
def self.output
[]
end
def self.return_value
# If your method provides a return value, you can describe here what it does
end
def self.authors
["brki", "jschmid"]
end
def self.is_supported?(platform)
platform == :ios
end
end
end
end
|
jschmid/UpdatePlistFromStrings-fastlane-plugin
|
lib/fastlane/plugin/updateplistfromstrings/helper/updateplistfromstrings_helper.rb
|
module Fastlane
module Helper
class UpdateplistfromstringsHelper
# class methods that you define here become available in your action
# as `Helper::UpdateplistfromstringsHelper.your_method`
#
end
end
end
|
jschmid/UpdatePlistFromStrings-fastlane-plugin
|
lib/fastlane/plugin/updateplistfromstrings/version.rb
|
<gh_stars>1-10
module Fastlane
module Updateplistfromstrings
VERSION = "1.0.2"
end
end
|
jschmid/UpdatePlistFromStrings-fastlane-plugin
|
spec/updateplistfromstrings_action_spec.rb
|
<filename>spec/updateplistfromstrings_action_spec.rb
describe Fastlane::Actions::UpdateplistfromstringsAction do
end
|
tka/rails-with-webpack
|
app/helpers/webpack_helper.rb
|
<reponame>tka/rails-with-webpack<filename>app/helpers/webpack_helper.rb<gh_stars>1-10
# rails 整合 webpack 用的 helper
# 開發環境要多跑一個 webpack-dev-server
require 'open-uri'
module WebpackHelper
class CantGetResuorceError < StandardError; end
def webpack_stylesheet_link_tag(*sources)
begin
sources = get_webpack_sources(sources, 'css')
stylesheet_link_tag(*sources)
rescue CantGetResuorceError => e
alert_cant_get_resource(e)
end
end
def webpack_javascript_include_tag(*sources)
begin
sources = get_webpack_sources(sources, 'js')
javascript_include_tag(*sources)
rescue CantGetResuorceError => e
alert_cant_get_resource(e.message)
end
end
private
def webpack_assets_manifest
@_manifest_file ||= if Rails.env.development?
cfg_file = File.join(Rails.root,"config","application.yml")
full_cfg = YAML.load( open(cfg_file,'r').read )
cfg = full_cfg["development"] || full_cfg["default"]
cfg["webpack_assets_host"]+"/webpack/manifest.json"
else
Rails.root.join('public','webpack','manifest.json')
end
manifest_data = open(@_manifest_file,'r'){|f| f.read}
JSON.parse(manifest_data)
end
def get_webpack_sources(sources, ext)
sources = sources.uniq.map do |source|
if source.is_a?(String)
source += ".#{ext}" unless source =~ /\.#{ext}\z/
path = webpack_assets_manifest[source]
if path
if Rails.env.development?
"//localhost:8080/webpack/#{path}"
else
"//#{Setting.assets_host}/webpack/#{path}"
end
else
raise CantGetResuorceError, "無法取得 webpack 資源: #{source}"
end
else
source
end
end
end
def alert_cant_get_resource(e)
# 線上環境直接噴掉, 其他的話在網頁跳出 alert mesage
if Rails.env.production?
raise CantGetResuorceError, e
else
"<script>alert(#{e.to_json})</script>".html_safe
end
end
end
|
tka/rails-with-webpack
|
lib/capistrano/tasks/webpack.rake
|
<gh_stars>1-10
namespace :deploy do
namespace :assets do
task :webpack do
on roles(:web) do
within release_path do
execute :npm, "install"
execute :webpack
end
end
end
end
end
before "deploy:assets:precompile", "deploy:assets:webpack"
|
mithucste30/solidus_cash_on_delivery
|
app/models/spree/payment_decorator.rb
|
Spree::Payment.class_eval do
has_one :adjustment, :as => :source, :dependent => :destroy
# for Cash on Delivery
def build_source
return if source_attributes.nil?
if payment_method and payment_method.respond_to?(:post_create)
payment_method.post_create(self)
end
if payment_method and payment_method.payment_source_class
self.source = payment_method.payment_source_class.new(source_attributes)
end
end
end
|
mithucste30/solidus_cash_on_delivery
|
app/models/spree/payment_method/cash_on_delivery.rb
|
<reponame>mithucste30/solidus_cash_on_delivery
module Spree
class PaymentMethod::CashOnDelivery < PaymentMethod
def payment_profiles_supported?
false # we do not want to show the confirm step
end
# def post_create(payment)
# payment.order.adjustments.each { |a| a.destroy if a.label == I18n.t(:shipping_and_handling) }
# payment.order.adjustments.create!(:amount => Spree::Config[:cash_on_delivery_charge],
# :source => payment,
# # :originator => payment,
# :label => I18n.t(:shipping_and_handling))
# end
def update_adjustment(adjustment, src)
adjustment.update_attribute_without_callbacks(:amount, Spree::Config[:cash_on_delivery_charge])
end
def authorize(*args)
ActiveMerchant::Billing::Response.new(true, "", {}, {})
end
def capture(payment, source, gateway_options)
ActiveMerchant::Billing::Response.new(true, "", {}, {})
end
def void(*args)
ActiveMerchant::Billing::Response.new(true, "", {}, {})
end
def actions
%w{capture void}
end
def can_capture?(payment)
return false if payment.completed?
payment.order.shipments.all? do |shipment|
shipment.state == 'shipped'
end
end
def can_void?(payment)
payment.state != 'void'
end
def source_required?
false
end
#def provider_class
# self.class
#end
def payment_source_class
nil
end
def method_type
'cash_on_delivery'
end
def cash_on_delivery?
true
end
def apply_adjustment(order)
label = I18n.t(:charge_label, scope: :on_delivery)
order.adjustments.each { |a| a.destroy if a.label == label }
order.adjustments.create!(
amount: compute_charge.call(order),
label: label,
order: order
)
order.update!
end
def compute_commission(order)
compute_charge.call(order)
end
private
def compute_charge
Rails.application.config.cash_on_delivery_charge if defined?(Rails)
end
end
end
|
mithucste30/solidus_cash_on_delivery
|
app/controllers/spree/checkout_controller_decorator.rb
|
Spree::CheckoutController.class_eval do
before_action :pay_on_delivery, only: :update
private
def pay_on_delivery
return unless params[:state] == 'payment'
return if params[:order].blank? || params[:order][:payments_attributes].blank?
pm_id = params[:order][:payments_attributes].first[:payment_method_id]
payment_method = Spree::PaymentMethod.find(pm_id)
payment_method.apply_adjustment(@order) if apply_adjustment?(payment_method)
rescue => e
@order.errors[:base] << "Something went wrong: #{e.try(:message)}"
render :edit
end
def apply_adjustment?(payment_method)
payment_method &&
payment_method.kind_of?(Spree::PaymentMethod::CashOnDelivery) &&
payment_method.respond_to?(:apply_adjustment)
end
end
|
mithucste30/solidus_cash_on_delivery
|
app/models/spree/shipment_decorator.rb
|
module Spree
Shipment.class_eval do
# Determines the appropriate +state+ according to the following logic:
#
# pending unless order is complete and +order.payment_state+ is +paid+
# shipped if already shipped (ie. does not change the state)
# ready all other cases
def determine_state(order)
return 'ready' if cash_on_delivery?
return 'canceled' if order.canceled?
return 'pending' unless order.can_ship?
return 'pending' if inventory_units.any? &:backordered?
return 'shipped' if state == 'shipped'
order.paid? || Spree::Config[:auto_capture_on_dispatch] ? 'ready' : 'pending'
end
private
def cash_on_delivery?
order.payments.any? do |payment|
payment.payment_method.respond_to?(:cash_on_delivery?)
end
end
end
end
|
mithucste30/solidus_cash_on_delivery
|
spree_cash_on_delivery.gemspec
|
<filename>spree_cash_on_delivery.gemspec
# encoding: UTF-8
Gem::Specification.new do |s|
s.platform = Gem::Platform::RUBY
s.name = 'solidus_cash_on_delivery'
s.version = '1.2.1'
s.summary = 'Solidus Cash On Delivery payment method for countries which provide goods and then collect cash'
s.description = 'In countries like India, one of the popular payment model is to collect cash while delivering goods. This extension adds COD payment method to Spree'
s.required_ruby_version = '>= 1.8.7'
s.author = '<NAME>'
s.email = '<EMAIL>'
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.require_path = 'lib'
s.requirements << 'none'
s.add_dependency 'solidus_core'
s.add_development_dependency 'capybara', '1.0.1'
s.add_development_dependency 'factory_girl'
s.add_development_dependency 'ffaker'
s.add_development_dependency 'rspec-rails', '~> 2.7'
s.add_development_dependency 'sqlite3'
end
|
mithucste30/solidus_cash_on_delivery
|
app/models/spree/app_configuration_decorator.rb
|
<gh_stars>0
Spree::AppConfiguration.class_eval do
preference :cash_on_delivery_charge, :decimal, :default => 5.2
end
|
richardcalahan/exportr
|
ext/exportr/extconf.rb
|
require 'mkmf'
create_makefile 'exportr'
|
richardcalahan/exportr
|
exportr.gemspec
|
<reponame>richardcalahan/exportr<gh_stars>1-10
$:.push File.expand_path("../lib", __FILE__)
require 'exportr/version'
Gem::Specification.new do |gem|
gem.name = 'exportr'
gem.version = Exportr::VERSION
gem.authors = ['<NAME>']
gem.email = ['<EMAIL>']
gem.description = 'Helps manage ruby application specific environment variables for multiple apps in development.'
gem.summary = 'Ruby environment variable manager'
gem.homepage = 'https://github.com/richardcalahan/exportr'
gem.files = `git ls-files`.split($/)
gem.extensions = Dir.glob 'ext/**/extconf.rb'
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ['lib']
gem.add_development_dependency 'rake'
gem.add_development_dependency 'rake-compiler'
gem.add_development_dependency 'rspec'
end
|
richardcalahan/exportr
|
lib/exportr.rb
|
begin
require 'exportr.bundle'
rescue LoadError
end
begin
require 'exportr.so'
rescue LoadError
end
module Exportr; end
|
richardcalahan/exportr
|
spec/exportr_spec.rb
|
<reponame>richardcalahan/exportr<filename>spec/exportr_spec.rb<gh_stars>1-10
require 'spec_helper'
describe Exportr do
it 'finds configuration file' do
File.exists?(Exportr.config_file).should == true
end
it 'reads configuration file' do
Exportr.read['FOO'].should == 'bar'
end
it 'wrote configuration file to ENV' do
ENV['FOO'].should == 'bar'
end
end
|
richardcalahan/exportr
|
lib/generators/exportr/exportr_generator.rb
|
<reponame>richardcalahan/exportr<filename>lib/generators/exportr/exportr_generator.rb<gh_stars>1-10
class ExportrGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def generate_initializer
copy_file 'exportr.yml', 'config/exportr.yml'
end
def mod_gitignore
return if File.read("#{Rails.root}/.gitignore").match(/config\/exportr.yml/)
File.open("#{Rails.root}/.gitignore", 'a+') do |f|
f.puts
f.puts '# Ignoring local env export'
f.puts 'config/exportr.yml'
f.puts
end
end
end
|
Wendyv510/eric_carle_books
|
lib/eric_carle_books/books.rb
|
class EricCarleBooks::Books
attr_accessor :title, :activity, :description
@@all = []
def initialize(title,description,activity)
@title = title
@description = description
@activity = activity
self.save
end
def self.all
@@all
end
def save
@@all << self
end
end
|
Wendyv510/eric_carle_books
|
lib/eric_carle_books.rb
|
<reponame>Wendyv510/eric_carle_books<filename>lib/eric_carle_books.rb
require "pry"
require "nokogiri"
require "open-uri"
require_relative "eric_carle_books/version"
require_relative "eric_carle_books/books"
require_relative "eric_carle_books/scraper"
require_relative "eric_carle_books/cli"
module EricCarleBooks
class Error < StandardError; end
# Your code goes here...
end
|
Wendyv510/eric_carle_books
|
lib/eric_carle_books/scraper.rb
|
<filename>lib/eric_carle_books/scraper.rb
class EricCarleBooks::Scraper
def self.get_books
@doc = Nokogiri::HTML(open("https://www.teachervision.com/authors/top-10-books-eric-carle"))
root_url = "https://www.teachervision.com"
titles = @doc.css("div.collection-title")
titles.each_with_index do |title, index|
title=title.text
description = @doc.css("div.collection-body")[index].text
if @doc.css("div.collection-body a")[index] == nil
activity = "Sorry, no link to this activity."
else
link= @doc.css("div.collection-body a")[index].attributes["href"].value
activity = root_url + link
end
book = EricCarleBooks::Books.new(title,description,activity)
end
end
end
|
Wendyv510/eric_carle_books
|
lib/eric_carle_books/cli.rb
|
class EricCarleBooks::CLI
def greeting
puts "Welcome, are you looking for the top 10 books <NAME> has written? Y/N"
input = gets.chomp
if input == "Y"
EricCarleBooks::Scraper.get_books
list_books
info_prompt
else
puts "Sorry, we can't help you."
end
end
def list_books
EricCarleBooks::Books.all.each_with_index do |book,i|
puts "#{i+1} #{book.title}"
end
end
def info_prompt
input = ""
while input != "exit"
puts "Please select a number to recieve a book description and activity link or exit."
input = gets.chomp
if input == "exit"
"Have a nice day."
elsif input.to_i-1<=EricCarleBooks::Books.all.size
book = EricCarleBooks::Books.all[input.to_i-1]
puts book.title
puts book.description
puts book.activity
end
end
end
end
|
mikelaning/chef-datadog
|
libraries/recipe_helpers.rb
|
<filename>libraries/recipe_helpers.rb
class Chef
# Helper class for Datadog Chef recipes
class Datadog
class << self
def agent_version(node)
dd_agent_version = node['datadog']['agent_version']
if dd_agent_version.respond_to?(:each_pair)
platform_family = node['platform_family']
# Unless explicitly listed, treat fedora and amazon as rhel
if !dd_agent_version.include?(platform_family) && ['fedora', 'amazon'].include?(platform_family)
platform_family = 'rhel'
end
dd_agent_version = dd_agent_version[platform_family]
end
if !dd_agent_version.nil? && dd_agent_version.match(/^[0-9]+\.[0-9]+\.[0-9]+((?:~|-)[^0-9\s-]+[^-\s]*)?$/)
if node['platform_family'] == 'suse' || node['platform_family'] == 'debian'
dd_agent_version = '1:' + dd_agent_version + '-1'
elsif node['platform_family'] == 'rhel' || node['platform_family'] == 'fedora' || node['platform_family'] == 'amazon'
dd_agent_version += '-1'
end
end
dd_agent_version
end
def agent_major_version(node)
# user-specified values
agent_major_version = node['datadog']['agent_major_version']
agent_version = agent_version(node)
if !agent_version.nil?
_epoch, major, _minor, _patch, _suffix, _release = agent_version.match(/([0-9]+:)?([0-9]+)\.([0-9]+)\.([0-9]+)([^-\s]+)?(?:-([0-9]+))?/).captures
if !agent_major_version.nil? && major.to_i != agent_major_version.to_i
raise "Provided (#{agent_major_version}) and deduced (#{major}) agent_major_version don't match"
end
ret = major.to_i
elsif !agent_major_version.nil?
ret = agent_major_version.to_i
else
# default to Agent 7
node.default['datadog']['agent_major_version'] = 7
ret = 7
end
ret
end
def api_key(node)
run_state_or_attribute(node, 'api_key')
end
def application_key(node)
run_state_or_attribute(node, 'application_key')
end
def ddagentuser_name(node)
run_state_or_attribute(node, 'windows_ddagentuser_name')
end
def ddagentuser_password(node)
run_state_or_attribute(node, 'windows_ddagentuser_password')
end
private
def run_state_or_attribute(node, attribute)
if node.run_state.key?('datadog') && node.run_state['datadog'].key?(attribute)
node.run_state['datadog'][attribute]
else
node['datadog'][attribute]
end
end
end
end
end
|
STRd6/apn_on_rails
|
spec/apn_on_rails/app/models/apn/group_notification_spec.rb
|
<filename>spec/apn_on_rails/app/models/apn/group_notification_spec.rb
require File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'spec_helper.rb')
describe APN::GroupNotification do
describe 'alert' do
it 'should trim the message to 150 characters' do
noty = APN::GroupNotification.new
noty.alert = 'a' * 200
noty.alert.should == ('a' * 147) + '...'
end
end
describe 'apple_hash' do
it 'should return a hash of the appropriate params for Apple' do
noty = APN::GroupNotification.first
noty.apple_hash.should == {"aps" => {"badge" => 5, "sound" => "my_sound.aiff", "alert" => "Hello!"},"typ" => "1"}
noty.custom_properties = nil
noty.apple_hash.should == {"aps" => {"badge" => 5, "sound" => "my_sound.aiff", "alert" => "Hello!"}}
noty.badge = nil
noty.apple_hash.should == {"aps" => {"sound" => "my_sound.aiff", "alert" => "Hello!"}}
noty.alert = nil
noty.apple_hash.should == {"aps" => {"sound" => "my_sound.aiff"}}
noty.sound = nil
noty.apple_hash.should == {"aps" => {}}
noty.sound = true
noty.apple_hash.should == {"aps" => {"sound" => "1.aiff"}}
end
end
describe 'to_apple_json' do
it 'should return the necessary JSON for Apple' do
noty = APN::GroupNotification.first
noty.to_apple_json.should be_same_meaning_as %{{"typ":"1","aps":{"badge":5,"sound":"my_sound.aiff","alert":"Hello!"}}}
end
end
describe 'message_for_sending' do
describe 'should create a binary message to be sent to Apple' do
subject {
noty = APN::GroupNotification.first
noty.custom_properties = nil
device = DeviceFactory.new(:token => token)
noty.message_for_sending(device)
}
let(:token) { '<KEY>' }
let(:device_token_binary_size) { [token.delete(' ')].pack('H*').size }
let(:token_part_header_length) { 1 + 2 } # Command length(1 byte) + Token length(2 byte)
let(:payload_part_header_length) { 2 } # Payload length(2 byte)
let(:boundaly_between_binary_and_payload) { token_part_header_length + device_token_binary_size + payload_part_header_length }
it 'should eq eqch binary part' do
subject[0...boundaly_between_binary_and_payload].should == fixture_value('message_for_sending.bin')[0...boundaly_between_binary_and_payload]
end
it 'should be same meaning as each payload part' do
subject[boundaly_between_binary_and_payload..-1].should be_same_meaning_as fixture_value('message_for_sending.bin')[boundaly_between_binary_and_payload..-1]
end
end
it 'should raise an APN::Errors::ExceededMessageSizeError if the message is too big' do
app = AppFactory.create
device = DeviceFactory.create({:app_id => app.id})
group = GroupFactory.create({:app_id => app.id})
device_grouping = DeviceGroupingFactory.create({:group_id => group.id,:device_id => device.id})
noty = GroupNotificationFactory.new(:group_id => group.id, :sound => true, :badge => nil)
noty.stub(:to_apple_json).and_return('_' * 257)
lambda {
noty.message_for_sending(device)
}.should raise_error(APN::Errors::ExceededMessageSizeError)
end
it 'should not raise any error if the payload is not too big' do
app = AppFactory.create
device = DeviceFactory.create({:app_id => app.id})
group = GroupFactory.create({:app_id => app.id})
device_grouping = DeviceGroupingFactory.create({:group_id => group.id,:device_id => device.id})
noty = GroupNotificationFactory.new(:group_id => group.id, :sound => true, :badge => nil)
noty.stub(:to_apple_json).and_return('_' * 256)
lambda {
noty.message_for_sending(device)
}.should_not raise_error
end
end
end
|
STRd6/apn_on_rails
|
lib/apn_on_rails/app/models/apn/group_notification.rb
|
<reponame>STRd6/apn_on_rails
class APN::GroupNotification < APN::Base
include ::ActionView::Helpers::TextHelper
extend ::ActionView::Helpers::TextHelper
serialize :custom_properties
belongs_to :group, :class_name => 'APN::Group'
has_one :app, :class_name => 'APN::App', :through => :group
has_many :device_groupings, :through => :group
validates_presence_of :group_id
def devices
self.group.devices
end
# Stores the text alert message you want to send to the device.
#
# If the message is over 150 characters long it will get truncated
# to 150 characters with a <tt>...</tt>
def alert=(message)
if !message.blank? && message.size > 150
message = truncate(message, :length => 150)
end
write_attribute('alert', message)
end
# Creates a Hash that will be the payload of an APN.
#
# Example:
# apn = APN::GroupNotification.new
# apn.badge = 5
# apn.sound = 'my_sound.aiff'
# apn.alert = 'Hello!'
# apn.apple_hash # => {"aps" => {"badge" => 5, "sound" => "my_sound.aiff", "alert" => "Hello!"}}
#
# Example 2:
# apn = APN::GroupNotification.new
# apn.badge = 0
# apn.sound = true
# apn.custom_properties = {"typ" => 1}
# apn.apple_hash # => {"aps" => {"badge" => 0, "sound" => 1.aiff},"typ" => "1"}
def apple_hash
result = {}
result['aps'] = {}
result['aps']['alert'] = self.alert if self.alert
result['aps']['badge'] = self.badge.to_i if self.badge
if self.sound
result['aps']['sound'] = self.sound if self.sound.is_a? String
result['aps']['sound'] = "1.aiff" if self.sound.is_a?(TrueClass)
end
if self.custom_properties
self.custom_properties.each do |key,value|
result["#{key}"] = "#{value}"
end
end
result
end
# Creates the JSON string required for an APN message.
#
# Example:
# apn = APN::Notification.new
# apn.badge = 5
# apn.sound = 'my_sound.aiff'
# apn.alert = 'Hello!'
# apn.to_apple_json # => '{"aps":{"badge":5,"sound":"my_sound.aiff","alert":"Hello!"}}'
def to_apple_json
self.apple_hash.to_json
end
# Creates the binary message needed to send to Apple.
def message_for_sending(device)
command = ['0'].pack('H') # Now, APN_ON_RAILS implements only "simple notification format".
token = device.to_hexa
token_length = [token.bytesize].pack('n')
payload = self.to_apple_json
payload_length = [payload.bytesize].pack('n')
message = command + token_length + token + payload_length + payload
raise APN::Errors::ExceededMessageSizeError.new(message) if payload.bytesize > 256
message
end
end # APN::Notification
|
STRd6/apn_on_rails
|
spec/apn_on_rails/app/models/apn/notification_spec.rb
|
<reponame>STRd6/apn_on_rails
require File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'spec_helper.rb')
describe APN::Notification do
describe 'alert' do
it 'should trim the message to 150 characters' do
noty = APN::Notification.new
noty.alert = 'a' * 200
noty.alert.should == ('a' * 147) + '...'
end
end
describe 'apple_hash' do
it 'should return a hash of the appropriate params for Apple' do
noty = APN::Notification.first
noty.apple_hash.should == {"aps" => {"badge" => 5, "sound" => "my_sound.aiff", "alert" => "Hello!"},"typ" => "1"}
noty.custom_properties = nil
noty.apple_hash.should == {"aps" => {"badge" => 5, "sound" => "my_sound.aiff", "alert" => "Hello!"}}
noty.badge = nil
noty.apple_hash.should == {"aps" => {"sound" => "my_sound.aiff", "alert" => "Hello!"}}
noty.alert = nil
noty.apple_hash.should == {"aps" => {"sound" => "my_sound.aiff"}}
noty.sound = nil
noty.apple_hash.should == {"aps" => {}}
noty.sound = true
noty.apple_hash.should == {"aps" => {"sound" => "1.aiff"}}
end
end
describe 'to_apple_json' do
it 'should return the necessary JSON for Apple' do
noty = APN::Notification.first
noty.to_apple_json.should be_same_meaning_as %{{"typ":"1","aps":{"badge":5,"sound":"my_sound.aiff","alert":"Hello!"}}}
end
end
describe 'message_for_sending' do
describe 'should create a binary message to be sent to Apple' do
subject {
noty = APN::Notification.first
noty.custom_properties = nil
noty.device = DeviceFactory.new(:token => token)
noty.message_for_sending
}
let(:token) { '<KEY>' }
let(:device_token_binary_size) { [token.delete(' ')].pack('H*').size }
let(:token_part_header_length) { 1 + 2 } # Command length(1 byte) + Token length(2 byte)
let(:payload_part_header_length) { 2 } # Payload length(2 byte)
let(:boundaly_between_binary_and_payload) { token_part_header_length + device_token_binary_size + payload_part_header_length }
it 'should eq each binary part' do
subject[0...boundaly_between_binary_and_payload].should == fixture_value('message_for_sending.bin')[0...boundaly_between_binary_and_payload]
end
it 'should be same meaning as each payload part' do
subject[boundaly_between_binary_and_payload..-1].should be_same_meaning_as fixture_value('message_for_sending.bin')[boundaly_between_binary_and_payload..-1]
end
end
it 'should raise an APN::Errors::ExceededMessageSizeError if the message is too big' do
noty = NotificationFactory.new(:device_id => DeviceFactory.create, :sound => true, :badge => nil)
noty.stub(:to_apple_json).and_return('_' * 257)
lambda {
noty.message_for_sending
}.should raise_error(APN::Errors::ExceededMessageSizeError)
end
it 'should not raise any error if the payload is not too big' do
noty = NotificationFactory.new(:device_id => DeviceFactory.create, :sound => true, :badge => nil)
noty.stub(:to_apple_json).and_return('_' * 256)
lambda {
noty.message_for_sending
}.should_not raise_error
end
end
describe 'send_notifications' do
it 'should warn the user the method is deprecated and call the corresponding method on APN::App' do
ActiveSupport::Deprecation.should_receive(:warn)
APN::App.should_receive(:send_notifications)
APN::Notification.send_notifications
end
end
end
|
jasherai/authlogic_bundle
|
templates/testing.rb
|
SOURCE = "vendor/plugins/authlogic_bundle" unless defined? SOURCE
load_template("#{SOURCE}/templates/helper.rb") unless self.respond_to? :file_inject
##############################
# RSpec
##############################
gem 'rspec', :lib => false, :version => '>= 1.2.6', :env => 'test'
gem 'rspec-rails', :lib => false, :version => '>= 1.2.6', :env => 'test'
gem 'remarkable', :lib => false, :version => '>=3.0.10', :env => 'test'
gem 'remarkable_activerecord', :lib => false, :version => '>=3.0.10', :env => 'test'
gem 'remarkable_rails', :lib => false, :version => '>=3.0.10', :env => 'test'
gem 'thoughtbot-shoulda', :lib => false, :version => '>=2.10.1',
:source => 'http://gems.github.com', :env => 'test'
gem 'thoughtbot-factory_girl', :lib => false, :version => '>=1.2.1',
:source => 'http://gems.github.com', :env => 'test'
rake 'gems:install', :sudo => true, :env => 'test'
# plugin 'rspec-rails', :submodule => git?,
# :git => 'git://github.com/dchelimsky/rspec-rails.git'
# plugin 'rspec', :submodule => git?,
# :git => 'git://github.com/dchelimsky/rspec.git'
# plugin 'factory_girl', :submodule => git?,
# :git => 'git://github.com/thoughtbot/factory_girl.git'
# plugin 'shoulda', :submodule => git?,
# :git => 'git://github.com/thoughtbot/shoulda.git'
generate :rspec
file 'spec/spec.opts', <<-CODE
--colour
--format progress
--format html:coverage/spec.html
--loadby mtime
--reverse
CODE
file_inject 'spec/spec_helper.rb', "require 'spec/rails'", <<-CODE
require 'remarkable_rails'
require 'shoulda'
require 'factory_girl'
CODE
##############################
# Cucumber
##############################
gem 'term-ansicolor', :lib => false, :version => '>=1.0.3', :env => 'test'
gem 'treetop', :lib => false, :version => '>=1.2.5', :env => 'test'
gem 'diff-lcs', :lib => false, :version => '>=1.1.2', :env => 'test'
gem 'nokogiri', :lib => false, :version => '>=1.2.3', :env => 'test'
gem 'builder', :lib => false, :version => '>=2.1.2', :env => 'test'
gem 'cucumber', :lib => false, :version => '>=0.3.1', :env => 'test'
gem 'webrat', :lib => 'webrat', :version => '>=0.4.4', :env => 'test'
gem 'bmabey-email_spec', :lib => 'email_spec', :version => '>=0.1.3',
:source => 'http://gems.github.com', :env => 'test'
gem 'ruby-debug-base', :lib => false, :version => '>=0.10.3', :env => 'test'
gem 'ruby-debug', :lib => false, :version => '>=0.10.3', :env => 'test'
rake 'gems:install', :sudo => true, :env => 'test'
generate :cucumber
file 'cucumber.yml', <<-CODE
default: -r features features
autotest: -r features --format pretty
autotest-all: -r features --format progress
CODE
file_append 'features/support/env.rb', <<-CODE
require 'email_spec/cucumber'
CODE
generate :email_spec
file 'features/step_definitions/custom_email_steps.rb', <<-CODE
CODE
file_inject 'spec/spec_helper.rb', "require 'spec/rails'", <<-CODE
require 'email_spec/helpers'
require 'email_spec/matchers'
CODE
file_inject 'spec/spec_helper.rb', "Spec::Runner.configure do |config|", <<-CODE
config.include(EmailSpec::Helpers)
config.include(EmailSpec::Matchers)
CODE
##############################
# RCov & Autotest
##############################
gem 'spicycode-rcov', :lib => 'rcov', :version => '>=0.8.2.1',
:source => 'http://gems.github.com', :env => 'test'
gem 'ZenTest', :lib => 'autotest', :version => '>=4.0.0', :env => 'test'
gem 'carlosbrando-autotest-notification', :lib => 'autotest_notification', :version => '>=1.9.1',
:source => 'http://gems.github.com', :env => 'test'
rake 'gems:install', :sudo => true, :env => 'test'
file 'spec/rcov.opts', <<-CODE
--exclude "spec/*,gems/*,features/*"
--rails
--aggregate "coverage.data"
CODE
run 'an-install'
#run 'an-uninstall'
file_append 'config/environments/test.rb', <<-CODE
ENV['AUTOFEATURE'] = "true"
ENV['RSPEC'] = "true"
CODE
if git?
git :submodule => "init"
git :submodule => "update"
git :add => "config lib script spec features cucumber.yml"
git :commit => "-m 'setup testing suite'"
end
|
jasherai/authlogic_bundle
|
app/helpers/application_helper.rb
|
<gh_stars>1-10
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
def secure_mail_to(email, name = nil)
return name if email.blank?
mail_to email, name, :encode => 'javascript'
end
def at(klass, attribute, options = {})
klass.human_attribute_name(attribute.to_s, options = {})
end
def openid_link
link_to at(User, :openid_identifier), "http://openid.net/"
end
end
|
jasherai/authlogic_bundle
|
templates/remote.rb
|
ENV['SCM'] = 'git' if yes?('Use git as scm? (y/n)')
def git?
ENV['SCM'] == 'git'
end
load_template("http://github.com/tsechingho/authlogic_bundle/raw/master/templates/git_init.rb") if git?
rails_edge_path = ask("If you want to symbol link rails edge, please give absolute path or press enter to skip:")
run "ln -s #{rails_edge_path} vendor/rails" unless rails_edge_path.blank?
plugin 'authlogic_bundle', :submodule => git?,
:git => 'git://github.com/tsechingho/authlogic_bundle.git'
load_template("vendor/plugins/authlogic_bundle/templates/base.rb")
load_template("vendor/plugins/authlogic_bundle/templates/testing.rb")
load_template("vendor/plugins/authlogic_bundle/templates/monitor.rb")
|
jasherai/authlogic_bundle
|
app/models/user.rb
|
class User < ActiveRecord::Base
acts_as_authentic do |c|
c.crypto_provider = Authlogic::CryptoProviders::BCrypt
c.validates_length_of_password_field_options = {:minimum => 4, :on => :update, :if => :require_password?}
c.validates_confirmation_of_password_field_options = {:minimum => 4, :on => :update, :if => (password_salt_field ? "#{password_salt_field}_changed?".to_sym : nil)}
c.validates_length_of_password_confirmation_field_options = {:minimum => 4, :on => :update, :if => :require_password?}
end
using_access_control
has_many :roles
attr_accessible :login, :email, :password, :password_confirmation, :openid_identifier
# Since UserSession.find and UserSession.save will trigger
# record.save_without_session_maintenance(false) and the 'updated_at', 'last_request_at'
# fields of user model will be updated every time by authlogic if record (user) found.
# We need to reset Authorization.current_user instead of giving the update privilege
# of user model to guest role, and use before_save filter in user model instead of
# after_find and before_save filters in UserSession model in case of other methods like
# reset_perishable_token! will call save_without_session_maintenance too.
before_save :set_current_user_for_model_security
def active?
self.state == 'active'
end
def signup!(user)
self.login = user[:login]
self.email = user[:email]
save_without_session_maintenance
end
# Since openid_identifier= will trigger openid authentication,
# we need to save with block to prevent double render/redirect error.
def activate!(user, &block)
unless user.blank?
self.password = <PASSWORD>[:password]
self.password_confirmation = <PASSWORD>[:<PASSWORD>]
self.openid_identifier = user[:openid_identifier]
end
self.state = 'active'
roles.build(:name => 'customer') if roles.empty?
save(true, &block)
end
# Since password reset doesn't need to change openid_identifier,
# we save without block as usual.
def reset_password!(user)
self.class.ignore_blank_passwords = false
self.password = user[:password]
self.password_confirmation = user[:password_confirmation]
save
end
def deliver_activation_instructions!
# skip reset perishable token since we don't set roles in signup!
reset_perishable_token! unless roles.blank?
UserMailer.deliver_activation_instructions(self)
end
def deliver_activation_confirmation!
reset_perishable_token!
UserMailer.deliver_activation_confirmation(self)
end
def deliver_password_reset_instructions!
reset_perishable_token!
UserMailer.deliver_password_reset_instructions(self)
end
def role_symbols
(roles || []).map { |r| r.name.to_sym }
end
def to_param
login.parameterize
end
protected
def set_current_user_for_model_security
Authorization.current_user = self
end
private
# Since we use attr_accessible or attr_protected,
# we should overwrite this method defined in authlogic_openid.
def map_saved_attributes(attrs)
attrs.each do |key, value|
send("#{key}=", value)
end
end
end
|
jasherai/authlogic_bundle
|
tasks/authlogic_bundle.rake
|
<reponame>jasherai/authlogic_bundle
$LOAD_PATH.unshift(RAILS_ROOT + '/vendor/plugins/cucumber/lib') if File.directory?(RAILS_ROOT + '/vendor/plugins/cucumber/lib')
namespace :authlogic_bundle do
plugin_path = "vendor/plugins/authlogic_bundle"
desc "Sync bundled files"
task :sync do
system "rsync -rbv #{plugin_path}/app/helpers/application_helper.rb app/helpers"
system "rsync -rbv #{plugin_path}/app/helpers/layout_helper.rb app/helpers"
system "rsync -ruv #{plugin_path}/config/authorization_rules.rb config"
system "rsync -ruv #{plugin_path}/config/initializers config"
system "rsync -ruv #{plugin_path}/config/notifier.yml config"
system "rsync -rbv #{plugin_path}/config/locales config"
system "rsync -ruv #{plugin_path}/cucumber.yml ."
# system "rsync -ruv #{plugin_path}/public ."
end
begin
require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:features, "Run Features of authlogic_bundle with Cucumber") do |t|
t.cucumber_opts = "--format pretty"
t.feature_pattern = "#{plugin_path}/features/**/*.feature"
t.step_pattern = "#{plugin_path}/features/**/*.rb"
end
task :features => 'db:test:prepare'
rescue LoadError
desc 'Cucumber rake task not available'
task :features do
abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin'
end
end
end
|
revolutionhealth/acts_as_recoverable
|
lib/recoverable_object.rb
|
<filename>lib/recoverable_object.rb
class RecoverableObject < ActiveRecord::Base
serialize :object_hash
def recover
load_from_hash(object_hash)
end
def recover!
result = recover
result.save
result.after_recover(self) if result.respond_to?(:after_recover)
self.destroy
result
end
def object=(object)
self.object_hash = get_object_hash(object)
self.recoverable_id = object.id
self.recoverable_type = object.class.name
self.deleted_at = Time.now
end
private
# Create a new object by object type and then set all of the attributes
# via setter methods to avoid restrictions on mass assignment.
def load_from_hash(hash)
return nil unless hash
result = hash[:type].constantize.new
hash[:attributes].each do |key, value|
result.send("#{key}=", value)
end
hash[:reflections].each do |name, values|
if values
if values.is_a?Array
reflection_objects = values.map { |h| load_from_hash(h) }
result.send("#{name}=", reflection_objects)
elsif values.is_a?Hash
reflection_object = load_from_hash(values)
result.send("#{name}=", reflection_object)
end
end
end
result
end
def get_object_hash(object)
return nil unless object
hash = { :type => object.class.name, :attributes => object.attributes, :reflections => {} }
object.class.reflections.each do |name, reflection|
if reflection.options[:dependent] == :destroy
if reflection.macro == :has_many
hash[:reflections][name] = []
Array(object.send(name)).each do |child|
hash[:reflections][name] << get_object_hash(child) unless child.nil?
end
elsif reflection.macro == :has_one or reflection.macro == :belongs_to
value = object.send(name)
hash[:reflections][name] = get_object_hash(value)
end
elsif reflection.macro == :has_and_belongs_to_many
ids_name = "#{name.to_s.singularize}_ids"
hash[:attributes][ids_name] = object.send(ids_name)
end
end
hash
end
end
|
revolutionhealth/acts_as_recoverable
|
test/fixtures/schema.rb
|
begin
ActiveRecord::Schema.define(:version => 1) do
create_table :articles, :force => true do |t|
t.string :name
t.string :type
t.timestamps
end
create_table :tags, :force => true do |t|
t.string :name
t.integer :article_id
t.timestamps
end
create_table :authors, :force => true do |t|
t.string :name
t.references :article
t.timestamps
end
create_table :comments, :force => true do |t|
t.text :content
t.references :article
t.timestamps
end
create_table :ratings, :force => true do |t|
t.integer :value
t.references :comment
t.timestamps
end
create_table :listings, :force => true do |t|
t.string :name
t.timestamps
end
create_table :locations, :force => true do |t|
t.string :address
t.timestamps
end
create_table :listings_locations, :force => true do |t|
t.references :listing, :location
t.timestamps
end
create_table :recoverable_objects do |t|
t.column :recoverable_id, :integer, :null => false
t.column :recoverable_type, :string, :limit => 255, :null => false
t.text :object_hash
t.column :deleted_at, :timestamp
t.timestamps
end
end
rescue => e
p e.message
end
|
revolutionhealth/acts_as_recoverable
|
acts_as_recoverable.gemspec
|
Gem::Specification.new do |s|
s.name = %q{acts_as_recoverable}
s.version = "1.0.4"
s.specification_version = 1 if s.respond_to? :specification_version=
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Revolution Health"]
s.autorequire = %q{acts_as_recoverable}
s.date = %q{2000-01-12}
s.description = %q{A plugin for ActiveRecord that allows for easy recovery of deleted models.}
s.email = %q{<EMAIL>}
s.extra_rdoc_files = ["README.rdoc"]
s.files = ["MIT-LICENSE","README.rdoc", "Rakefile","init.rb","install.rb","uninstall.rb","generators/recoverable_objects_migration/templates/migration.rb","generators/recoverable_objects_migration/recoverable_objects_migration_generator.rb","generators/recoverable_objects_migration/USAGE",
"lib/acts_as_recoverable.rb","lib/recoverable_object.rb","tasks/acts_as_recoverable_tasks.rake"]
s.has_rdoc = true
s.homepage = %q{http://}
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.1}
s.summary = %q{A plugin for ActiveRecord that allows for easy recovery of deleted models.}
s.add_dependency("activerecord", "~> 2.0")
end
|
revolutionhealth/acts_as_recoverable
|
lib/acts_as_recoverable.rb
|
<gh_stars>1-10
module Patch
module Acts
module Recoverable
def acts_as_recoverable
return if self.included_modules.include?(InstanceMethods)
include InstanceMethods
end
module InstanceMethods
def self.included(base)
base.class_eval do
before_destroy :create_recoverable_object_for
extend Patch::Acts::Recoverable::SingletonMethods
end
end
def create_recoverable_object_for(object = self, results = {})
RecoverableObject.create(:object => object)
end
def destroy!
def self.create_recoverable_object_for; end # is there a cleaner way to do this?
destroy
end
end
module SingletonMethods
def find_and_recover(id)
ro = RecoverableObject.find(:first, :conditions => ["recoverable_id = ? and recoverable_type = ?", id, self.to_s])
if ro
ro.recover!
else
raise ActiveRecord::ActiveRecordError.new("Could not find recoverable with recoverable_id = #{id} and recoverable_type = #{self.to_s}")
end
end
end
end
end
end
ActiveRecord::Base.send(:extend, Patch::Acts::Recoverable)
|
revolutionhealth/acts_as_recoverable
|
test/fixtures/models.rb
|
<gh_stars>1-10
class Article < ActiveRecord::Base
acts_as_recoverable
has_many :comments, :dependent => :destroy
has_many :authors
has_many :tags, :dependent => :destroy
end
class HealthArticle < Article
end
class TechnicalArticle < Article
end
class Tag < ActiveRecord::Base
acts_as_recoverable
belongs_to :article
end
class Author < ActiveRecord::Base
belongs_to :article
end
class Comment < ActiveRecord::Base
belongs_to :article
has_many :ratings, :dependent => :destroy
end
class Rating < ActiveRecord::Base
belongs_to :comment
end
class Listing < ActiveRecord::Base
acts_as_recoverable
has_and_belongs_to_many :locations
end
class Location < ActiveRecord::Base
has_and_belongs_to_many :listings
end
|
revolutionhealth/acts_as_recoverable
|
generators/recoverable_objects_migration/templates/migration.rb
|
<gh_stars>1-10
class RecoverableObjectsMigration < ActiveRecord::Migration
def self.up
create_table :recoverable_objects do |t|
t.column :recoverable_id, :integer, :null => false
t.column :recoverable_type, :string, :limit => 255, :null => false
t.text :object_hash
t.column :deleted_at, :timestamp
t.timestamps
end
end
def self.down
drop_table :recoverable_objects
end
end
|
revolutionhealth/acts_as_recoverable
|
test/acts_as_recoverable_test.rb
|
<filename>test/acts_as_recoverable_test.rb
require File.join(File.dirname(__FILE__), 'test_helper')
class ActsAsRecoverableTest < Test::Unit::TestCase
def teardown
[Tag, Article, Comment, RecoverableObject, Rating, Comment, Listing, Location].each do |klass|
klass.all.each { |a| a.destroy }
end
end
def test_factories
a = article(2, :name => 'hackery')
a.save
a.reload
assert_equal 2, a.comments.size
end
def test_should_be_removed_from_finds_when_destroyed
a = article(2, :name => 'hack1')
a.destroy
assert_nil Article.find_by_name('hack1')
assert_nil Comment.find_by_content('c1')
end
def test_should_be_added_to_recoverable_objects_when_destroyed
a = article(0, :name => 'oooh')
a.destroy
assert_equal 1, RecoverableObject.all.size
end
def test_should_not_be_added_to_recoverable_objects_when_destroyed!
a = article(0, :name => 'gone for good')
a.destroy!
assert_equal 0, RecoverableObject.count
end
def test_should_recover_objects_using_finder_class_method
#create two articles, with one comment and one rating
article_one = article(0, :name => 'article one')
article_one_id = article_one.id
article_two = article(0, :name => 'article two')
article_two_id = article_two.id
comment_one = comment()
rating_one = rating()
comment_one.ratings << rating_one
comment_two = comment()
rating_two = rating()
comment_two.ratings << rating_two
article_one.comments << comment_one
article_two.comments << comment_two
#check to see that there are 2 articles, comments, and ratings
assert_equal 2, Article.count
assert_equal 2, Comment.count
assert_equal 2, Rating.count
assert_equal 1, article_one.reload.comments.size
#destroy the first article
article_one.destroy
#assert that there is one recoverable in the recoverable_objects
assert_equal 1, RecoverableObject.count
#assert that one article, one comment, and one rating did get deleted
assert_equal 1, Article.count
assert_equal 1, Comment.count
assert_equal 1, Rating.count
#add a Tag to the second article. Tag also acts_as_recoverable.
article_two.tags << Tag.create(:name => "My First Tag")
assert_equal 1, Article.count
assert_equal 1, Comment.count
assert_equal 1, Rating.count
assert_equal 1, Tag.count
#destroy the second article
article_two.destroy
#assert there are no articles and tags
assert_equal 0, Article.count
assert_equal 0, Tag.count
#assert there are 3 recoverable records, two articles and one tag
assert_equal 3, RecoverableObject.count
types = RecoverableObject.find(:all).collect {|obj|obj.recoverable_type}
assert_equal ["Article", "Article", "Tag"], types
#Try to recover the first article
Article.find_and_recover(article_one_id)
#Make sure that one article was restored
assert_equal 1, Article.count
assert_equal 1, Comment.count
assert_equal 1, Rating.count
assert_equal 2, RecoverableObject.count
#Make sure that the restored article's id is equal to the original id of the article
assert Article.find(article_one_id)
assert Article.find(:first).id, Article.find(article_one_id).id
#Recover the second article
Article.find_and_recover(article_two_id)
assert Article.find(article_two_id)
#Make sure both articles, comments, and ratings are restored
assert_equal 2, Article.count
assert_equal 2, Comment.count
assert_equal 2, Rating.count
assert_equal 1, Tag.count
#The Tag recoverable should still be in the table since we didn't explicitly recover it
assert_equal 1, RecoverableObject.count
assert_equal "Tag", RecoverableObject.find(:first).recoverable_type
end
def test_should_restore_the_same_id_and_timestamps
article_one = article(0, :name => 'article one')
article_one_id = article_one.id
article_one.name = "article one change"
article_one.save
updated_at = article_one.updated_at
created_at = article_one.created_at
article_one.destroy
article = Article.find_and_recover(article_one_id)
assert article
assert_equal article_one_id, article.id
assert_equal updated_at.to_s, article.updated_at.to_s
assert_equal created_at.to_s, article.created_at.to_s
end
def test_should_work_with_sti
health = HealthArticle.create(:name => "Health Article")
health_id = health.id
technical = TechnicalArticle.create(:name => "Technical Article")
health.destroy
technical.destroy
assert RecoverableObject.find(:first).deleted_at
health = HealthArticle.find_and_recover(health_id)
assert health
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/http.rb
|
require 'net/http'
class Coinmux::Http
include Singleton, Coinmux::Facades
def get(host, path, options = {:disable_cache => false})
begin
info "HTTP GET Request #{host}#{path}"
if options[:disable_cache]
do_get(host, path)
else
with_cache(host, path) do
do_get(host, path)
end
end
rescue Coinmux::Error => e
raise e
rescue SocketError => e
raise Coinmux::Error, e.message
rescue StandardError => e
puts e, e.backtrace
raise Coinmux::Error, "Unknown error: #{e.message}"
end
end
def post(host, path, data = {})
begin
info "HTTP POST Request #{host}#{path}"
do_post(host, path, data)
rescue Coinmux::Error => e
raise e
rescue SocketError => e
raise Coinmux::Error, e.message
rescue StandardError => e
puts e, e.backtrace
raise Coinmux::Error, "Unknown error: #{e.message}"
end
end
private
def do_post(host, path, data)
uri = URI("#{host}#{path}")
response = Net::HTTP.post_form(uri, data)
info "HTTP POST Response #{response.code}"
raise Coinmux::Error, "Invalid response code: #{response.code}" if response.code.to_s != '200'
# debug "HTTP POST Response Content #{response.body}"
response.body
end
def do_get(host, path)
uri = URI("#{host}#{path}")
response = Net::HTTP.get_response(uri)
info "HTTP GET Response #{response.code}"
raise Coinmux::Error, "Invalid response code: #{response.code}" if response.code.to_s != '200'
# debug "HTTP GET Response Content #{response.body}"
response.body
end
def cache
@cache ||= {}
end
def clear_cache
cache.clear
end
def with_cache(host, path, &block)
key = [host, path]
result = cache[key]
info "HTTP cached? #{!result.nil?}"
if result.nil?
result = cache[key] = yield
end
result
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/version.rb
|
module Coinmux
VERSION = "0.2.1"
BANNER = "Coinmux - Decentralized, Trustless, Anonymous and Open Bitcoin Mixer"
end
|
michaelgpearce/coinmux
|
lib/coinmux/validation_model.rb
|
module Coinmux::ValidationModel
class Errors
def initialize
@errors = {}
end
def [](key)
@errors[key.to_sym] ||= []
end
def full_messages
@errors.collect { |key, value| "#{key.to_s.gsub('_', ' ')} #{value}" }
end
def clear
@errors.clear
end
def empty?
@errors.values.flatten.empty?
end
end
module ClassMethods
def validate(method, options = {})
method = method.to_sym
method_validations = validations[method] ||= []
method_validations << options.dup
end
def validations
@validations ||= {}
end
def validates(*attributes)
options = attributes.pop
attributes.each do |attribute|
validate(:validate, options.merge(attribute: attribute))
end
end
end
module InstanceMethods
def valid?
errors.clear
self.class.validations.each do |method_name, array_of_options|
array_of_options.each do |options|
needs_validation =
(options[:if].nil? && options[:unless].nil?) ||
(options[:if] && send(options[:if])) ||
(options[:unless] && !send(options[:unless]))
if needs_validation
method(method_name).arity == 0 ? send(method_name) : send(method_name, options)
end
end
end
errors.empty?
end
def errors
@errors ||= Errors.new
end
private
def validate(options)
attribute = options[:attribute]
if !options[:presence].nil?
errors[attribute] << "is not present" if options[:presence] && send(attribute).blank?
errors[attribute] << "is present" if !options[:presence] && send(attribute).present?
end
end
end
def self.included(base)
base.send(:include, InstanceMethods)
base.send(:extend, ClassMethods)
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/data_store/memory.rb
|
class Coinmux::DataStore::Memory < Coinmux::DataStore::Base
def initialize(coin_join_uri)
super(coin_join_uri)
@data_store ||= Hash.new
end
def clear
@data_store.clear
end
protected
def write(key, value)
@data_store[key] = value
end
def read(key)
@data_store[key]
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/p2p_bootstrap.rb
|
class Coinmux::DataStore
include Singleton
import 'java.io.IOException'
import 'net.tomp2p.p2p.Peer'
import 'net.tomp2p.p2p.PeerMaker'
import 'net.tomp2p.peers.Number160'
import 'java.util.Random'
def startup
@peer = PeerMaker.new(Number160.new(Random.new)).setPorts(14141).makeAndListen()
@peer.getConfiguration().setBehindFirewall(true)
end
def shutdown
@peer.shutdown if @peer
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/application/input_validator.rb
|
class Coinmux::Application::InputValidator
include Coinmux::Facades
REQUIRED_ATTRS = [:data_store, :input_private_key, :amount, :participants, :change_address, :output_address]
OPTIONAL_ATTRS = [:coin_join_uri]
ATTRS = REQUIRED_ATTRS + OPTIONAL_ATTRS
attr_accessor *ATTRS
def initialize(params)
params.assert_keys!(required: REQUIRED_ATTRS, optional: OPTIONAL_ATTRS)
params.each do |key, value|
send("#{key}=", value)
end
end
def validate
errors = []
begin
Coinmux::CoinJoinUri.parse(coin_join_uri) if coin_join_uri
rescue Coinmux::Error => e
errors << ErrorMessage.new(:coin_join_uri, "is invalid", "CoinJoin URI is invalid")
end
hex_private_key = begin
bitcoin_crypto_facade.private_key_to_hex!(input_private_key)
rescue Coinmux::Error => e
errors << ErrorMessage.new(:input_private_key, "is invalid")
nil
end
coin_join = Coinmux::Message::CoinJoin.build(data_store, amount: amount, participants: participants)
coin_join.valid?
errors += coin_join.errors[:amount].collect { |e| ErrorMessage.new(:amount, e) }
errors += coin_join.errors[:participants].collect { |e| ErrorMessage.new(:participants, e) }
input = Coinmux::Message::Input.build(coin_join, private_key: hex_private_key || '', change_address: change_address)
input.valid?
errors += input.errors[:address].collect { |e| ErrorMessage.new(:input_address, e) } if hex_private_key
errors += input.errors[:change_address].collect { |e| ErrorMessage.new(:change_address, e) }
output = Coinmux::Message::Output.build(coin_join, address: output_address)
output.valid?
errors += output.errors[:address].collect { |e| ErrorMessage.new(:output_address, e) }
errors
end
class ErrorMessage
attr_accessor :key, :message, :full_message
def initialize(key, message, full_message = "#{key.to_s.gsub(/_/, ' ').capitalize} #{message}")
self.key, self.message, self.full_message = key, message.to_s, full_message
end
def to_s
full_message
end
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/assert_keys.rb
|
class Hash
def assert_keys!(options)
required = options[:required] || []
required = [required] unless required.is_a?(Array)
optional = options[:optional] || []
optional = [optional] unless optional.is_a?(Array)
unknown = keys - (required + optional)
raise "Unknown keys: #{unknown.join(', ')}" unless unknown.empty?
missing = required - keys
raise "Required keys missing: #{missing.join(', ')}" unless missing.empty?
end
end
|
michaelgpearce/coinmux
|
spec/message/coin_join_spec.rb
|
require 'spec_helper'
describe Coinmux::Message::CoinJoin do
before do
fake_all_network_connections
end
let(:amount) { SATOSHIS_PER_BITCOIN }
let(:participants) { 2 }
let(:participant_transaction_fee) { DEFAULT_TRANSACTION_FEE / 2 }
let(:version) { Coinmux::Message::CoinJoin::VERSION }
describe "validations" do
let(:message) { build(:coin_join_message, amount: amount, participants: participants, participant_transaction_fee: participant_transaction_fee, version: version) }
subject { message.valid? }
it "is valid with default data" do
subject
expect(subject).to be_true
end
describe "#participants_numericality" do
context "with non numeric value" do
let(:participants) { "non-numeric" }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:participants]).to include("is not an integer")
end
end
context "with less than 2" do
let(:participants) { 1 }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:participants]).to include("must be at least 2")
end
end
end
describe "#amount_numericality" do
context "with non numeric value" do
let(:amount) { "non-numeric" }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:amount]).to include("is not a decimal number")
end
end
context "with less than or equal 0" do
let(:amount) { [0, -1].sample }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:amount]).to include("must be greater than 0")
end
end
end
describe "#participant_transaction_fee_numericality" do
context "with non numeric value" do
let(:participant_transaction_fee) { "non-numeric" }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:participant_transaction_fee]).to include("is not an integer")
end
end
context "with less than 0" do
let(:participant_transaction_fee) { -1 }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:participant_transaction_fee]).to include("may not be a negative amount")
end
end
context "with greater than DEFAULT_TRANSACTION_FEE" do
let(:participant_transaction_fee) { DEFAULT_TRANSACTION_FEE + 1 }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:participant_transaction_fee]).to include("may not be greater than #{DEFAULT_TRANSACTION_FEE}")
end
end
end
describe "#version_matches" do
context "with version other than VERSION" do
let(:version) { Coinmux::Message::CoinJoin::VERSION - 1 }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:version]).to include("must be #{Coinmux::Message::CoinJoin::VERSION}")
end
end
end
end
describe "associations" do
let(:message) { build(:coin_join_message) }
describe "#inputs" do
it "is a read-write list association" do
expect(message.inputs.value).to eq([])
expect(message.inputs.type).to eq(:list)
expect(data_store.identifier_can_insert?(message.inputs.data_store_identifier)).to be_true
expect(data_store.identifier_can_request?(message.inputs.data_store_identifier)).to be_true
end
end
describe "#outputs" do
it "is a read-write list association" do
expect(message.outputs.value).to eq([])
expect(message.outputs.type).to eq(:list)
expect(data_store.identifier_can_insert?(message.outputs.data_store_identifier)).to be_true
expect(data_store.identifier_can_request?(message.outputs.data_store_identifier)).to be_true
end
end
describe "#message_verification" do
it "is a read-only fixed association" do
expect(message.message_verification.value).to eq(nil)
expect(message.message_verification.type).to eq(:fixed)
expect(data_store.identifier_can_insert?(message.message_verification.data_store_identifier)).to be_false
expect(data_store.identifier_can_request?(message.message_verification.data_store_identifier)).to be_true
end
end
describe "#transaction" do
it "is a read-only fixed association" do
expect(message.transaction.value).to eq(nil)
expect(message.transaction.type).to eq(:fixed)
expect(data_store.identifier_can_insert?(message.transaction.data_store_identifier)).to be_false
expect(data_store.identifier_can_request?(message.transaction.data_store_identifier)).to be_true
end
end
describe "#transaction_signatures" do
it "is a read-write list association" do
expect(message.transaction_signatures.value).to eq([])
expect(message.transaction_signatures.type).to eq(:list)
expect(data_store.identifier_can_insert?(message.transaction_signatures.data_store_identifier)).to be_true
expect(data_store.identifier_can_request?(message.transaction_signatures.data_store_identifier)).to be_true
end
end
describe "#status" do
it "is a read-only variable association" do
expect(message.status.value).to eq(nil)
expect(message.status.type).to eq(:variable)
expect(data_store.identifier_can_insert?(message.status.data_store_identifier)).to be_false
expect(data_store.identifier_can_request?(message.status.data_store_identifier)).to be_true
end
end
end
describe "#build" do
subject { Coinmux::Message::CoinJoin.build(data_store, amount: amount, participants: participants) }
it "builds valid input" do
input = subject
expect(input.valid?).to be_true
end
end
describe "#from_json" do
let(:message) { build(:coin_join_message, amount: amount, participants: participants, participant_transaction_fee: participant_transaction_fee, version: version) }
let(:json) do
{
version: message.version,
identifier: message.identifier,
message_public_key: message.message_public_key,
amount: message.amount,
participants: message.participants,
participant_transaction_fee: message.participant_transaction_fee,
inputs: message.inputs.data_store_identifier,
message_verification: message.message_verification.data_store_identifier,
outputs: message.outputs.data_store_identifier,
transaction: message.transaction.data_store_identifier,
transaction_signatures: message.transaction_signatures.data_store_identifier,
outputs: message.outputs.data_store_identifier,
status: message.status.data_store_identifier
}.to_json
end
subject do
Coinmux::Message::CoinJoin.from_json(json, data_store)
end
it "creates a valid input" do
expect(subject).to_not be_nil
expect(subject.valid?).to be_true
expect(subject.version).to eq(message.version)
expect(subject.identifier).to eq(message.identifier)
expect(subject.message_public_key).to eq(message.message_public_key)
expect(subject.amount).to eq(message.amount)
expect(subject.participants).to eq(message.participants)
expect(subject.participant_transaction_fee).to eq(message.participant_transaction_fee)
expect(subject.inputs.data_store_identifier).to eq(message.inputs.data_store_identifier)
expect(subject.inputs.value).to eq([])
expect(subject.message_verification.data_store_identifier).to eq(message.message_verification.data_store_identifier)
expect(subject.message_verification.value).to be_nil
expect(subject.outputs.data_store_identifier).to eq(message.outputs.data_store_identifier)
expect(subject.outputs.value).to eq([])
expect(subject.transaction.data_store_identifier).to eq(message.transaction.data_store_identifier)
expect(subject.transaction.value).to be_nil
expect(subject.transaction_signatures.data_store_identifier).to eq(message.transaction_signatures.data_store_identifier)
expect(subject.transaction_signatures.value).to eq([])
expect(subject.status.data_store_identifier).to eq(message.status.data_store_identifier)
expect(subject.status.value).to be_nil
end
end
describe "#message_verification_valid?" do
let(:coin_join) { build(:coin_join_message, :with_message_verification) }
let(:prefix) { :the_prefix }
let(:keys) { %w(foo bar) }
let(:message_identifier) { coin_join.message_verification.value.message_identifier }
let(:message_verification) { digest_facade.hex_message_digest(prefix, message_identifier, 'foo', 'bar') }
before do
expect(coin_join.director?).to be_true
expect(coin_join.message_verification.created_with_build?).to be_true
end
subject do
coin_join.message_verification_valid?(prefix, message_verification, *keys)
end
context "with matching identifier and keys" do
it "returns true" do
expect(subject).to be_true
end
end
context "with incorrect identifier" do
let(:message_identifier) { "incorrect-identifier" }
it "returns false" do
expect(subject).to be_false
end
end
context "with incorrect key" do
let(:keys) { %w(foot bart) }
it "returns false" do
expect(subject).to be_false
end
end
end
describe "#build_message_verification" do
let(:coin_join) do
build(:coin_join_message, :with_inputs, :with_message_verification).tap do |coin_join|
# not realistic to be the director and have a built input, but ok for testing
coin_join.inputs.value.first.created_with_build = true
end
end
let(:prefix) { :a_valid_prefix }
let(:keys) { %w(foo bar) }
let(:message_identifier) { coin_join.message_verification.value.message_identifier }
let(:input) { coin_join.inputs.value.detect(&:created_with_build?) }
before do
expect(coin_join.director?).to be_true
expect(coin_join.message_verification.created_with_build?).to be_true
expect(input).to_not be_nil
end
subject do
coin_join.build_message_verification(prefix, *keys)
end
context "with valid data" do
it "builds the correct verification message" do
expect(subject).to eq(digest_facade.hex_message_digest(prefix, message_identifier, *keys))
end
end
end
describe "#build_transaction_inputs" do
let(:coin_join) { build(:coin_join_message, :with_inputs, :with_message_verification, :with_outputs, :with_transaction) }
before do
stub_bitcoin_network_for_coin_join(coin_join)
end
subject { coin_join.build_transaction_inputs }
context "when in valid state" do
it "maps input transactions for address" do
expect(subject).to eq(coin_join.inputs.value.inject([]) do |acc, input|
acc += coin_join.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
end
end
describe "#build_transaction_outputs" do
let(:coin_join) { build(:coin_join_message, :with_inputs, :with_message_verification, :with_outputs, :with_transaction) }
before do
stub_bitcoin_network_for_coin_join(coin_join)
end
subject { coin_join.build_transaction_outputs }
context "when in valid state" do
context "with change addresses on input" do
it "maps output address and change address" do
expected = coin_join.outputs.value.collect do |output|
{ 'address' => output.address, 'amount' => coin_join.amount, 'identifier' => output.transaction_output_identifier }
end
expected += coin_join.inputs.value.collect do |input|
unspent_input_amount = bitcoin_network_facade.unspent_inputs_for_address(input.address).values.inject(&:+)
change_amount = unspent_input_amount - coin_join.amount - coin_join.participant_transaction_fee
{ 'address' => input.change_address, 'amount' => change_amount, 'identifier' => input.change_transaction_output_identifier }
end
expect(subject).to eq(expected)
end
end
context "with no change addresses on input" do
before do
coin_join.inputs.value.each do |input|
input.change_address = nil
end
end
it "maps output address with no change address" do
expected = coin_join.outputs.value.collect do |output|
{ 'address' => output.address, 'amount' => coin_join.amount, 'identifier' => output.transaction_output_identifier }
end
expect(subject).to eq(expected)
end
end
end
end
describe "#retrieve_unspent_transaction_inputs" do
let(:message) { build(:coin_join_message) }
let(:unspent_inputs) do
{
{ id: "a", index: 4 } => 10,
{ id: "b", index: 0 } => 20,
{ id: "c", index: 3 } => 15,
}
end
subject { message.retrieve_unspent_transaction_inputs(unspent_inputs, minimum_amount) }
context "with no unspect transactions" do
let(:minimum_amount) { 45 }
let(:unspent_inputs) { {} }
it "raises error" do
expect { subject }.to raise_error(Coinmux::Error)
end
end
context "with minimum_amount equal all transactions" do
let(:minimum_amount) { 45 }
it "retrieves transaction" do
expect(subject).to eq([{ id: "b", index: 0, amount: 20 }, { id: "c", index: 3, amount: 15 }, { id: "a", index: 4, amount: 10 }])
end
end
context "with minimum_amount greater than all transactions" do
let(:minimum_amount) { 46 }
it "raises error" do
expect { subject }.to raise_error(Coinmux::Error)
end
end
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/pki.rb
|
<reponame>michaelgpearce/coinmux<filename>lib/coinmux/pki.rb
require 'openssl'
class Coinmux::PKI
include Singleton
def generate_keypair
pki = OpenSSL::PKey::RSA.new(2048)
private_key = pki.to_s
public_key = pki.public_key.to_s
[private_key, public_key]
end
def public_encrypt(public_key, clear_text)
OpenSSL::PKey::RSA.new(public_key).public_encrypt(clear_text, OpenSSL::PKey::RSA::PKCS1_PADDING)
end
def private_encrypt(private_key, clear_text)
OpenSSL::PKey::RSA.new(private_key).private_encrypt(clear_text, OpenSSL::PKey::RSA::PKCS1_PADDING)
end
def public_decrypt(public_key, encrypted_text)
OpenSSL::PKey::RSA.new(public_key).public_decrypt(encrypted_text, OpenSSL::PKey::RSA::PKCS1_PADDING)
end
def private_decrypt(private_key, encrypted_text)
OpenSSL::PKey::RSA.new(private_key).private_decrypt(encrypted_text, OpenSSL::PKey::RSA::PKCS1_PADDING)
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/data_store/file.rb
|
require 'fileutils'
class Coinmux::DataStore::File < Coinmux::DataStore::Base
def initialize(coin_join_uri)
super(coin_join_uri)
path = if path_override = coin_join_uri.params['path']
path_override = File.expand_path(path_override)
FileUtils.mkdir_p(path_override)
path_override
else
Coinmux::FileUtil.root_mkdir_p('tmp', 'file_data_store')
end
@data_store ||= Diskcached.new(path, DATA_TIME_TO_LIVE)
end
def clear
@data_store.flush
end
protected
def write(key, value)
@data_store.set(key, value)
value
end
def read(key)
begin
@data_store.get(key)
rescue Diskcached::NotFound
nil
end
end
# @author <NAME> <<EMAIL>>
class Diskcached
# version for gem
VERSION = '1.1.0'
# disk location for cache store
attr_reader :store
# cache timeout
attr_reader :timeout
# time of last #garbage_collect
attr_reader :gc_last
# should auto_garbage_collect
attr_reader :gc_auto
# how often to auto_garbage_collect
attr_reader :gc_time
# initialize object
# - set #store to passed or default ('/tmp/cache')
# - set #timeout to passed or default ('600')
# - set #gc_last to current time
# - run #ensure_store_directory
def initialize store="/tmp/cache", timeout=600, autogc=true
@store = store
@timeout = timeout
if timeout.nil?
@gc_last, @gc_time = nil
@gc_auto = false
else
@gc_last = Time.now
@gc_auto = autogc
@gc_time = (timeout < 600 ? timeout : 600)
end
ensure_store_directory
end
# return true if cache with 'key' is expired
def expired? key
return false if timeout.nil?
mtime = read_cache_mtime(key)
return (mtime.nil? || mtime+timeout <= Time.now)
end
# expire cache with 'key'
def delete key
File.delete( cache_file(key) ) if File.exists?( cache_file(key) )
end
# expire (delete) all caches in #store directory
def flush
Dir[ File.join( store, '*.cache' ) ].each do |file|
File.delete(file)
end
end
# flush expired caches if garbage collection
# hasn't been run recently
def flush_expired
if gc_last && gc_time && gc_last+gc_time <= Time.now
flush_expired!
end
end
# flash expired caches, ingoring when garbage
# collection was last run
def flush_expired!
Dir[ File.join( store, "*.cache" ) ].each do |f|
if (File.mtime(f)+timeout) <= Time.now
File.delete(f)
end
end
@gc_last = Time.now
end
# create and read cache with 'key'
# - creates cache if it doesn't exist
# - reads cache if it exists
def cache key
begin
if expired?(key)
content = Proc.new { yield }.call
set( key, content )
end
content ||= get( key )
return content
rescue LocalJumpError
return nil
end
end
# set cache with 'key'
# - run #auto_garbage_collect
# - creates cache if it doesn't exist
def set key, value
begin
write_cache_file( key, Marshal::dump(value) )
flush_expired if gc_auto
return true
rescue
flush_expired if gc_auto
return false
end
end
alias :add :set # for memcached compatability
alias :replace :set # for memcached compatability
# get cache with 'key'
# - reads cache if it exists and isn't expired
# or raises Diskcache::NotFound
# - if 'key' is an Array returns only keys
# which exist and aren't expired, it raises
# Diskcache::NotFound if none are available
def get key
begin
if key.is_a? Array
hash = {}
key.each do |k|
hash[k] = Marshal::load(read_cache_file(k)) unless expired?(k)
end
flush_expired if gc_auto
return hash unless hash.empty?
else
flush_expired if gc_auto
return Marshal::load(read_cache_file(key)) unless expired?(key)
end
raise Diskcached::NotFound
rescue
raise Diskcached::NotFound
end
end
# returns path to cache file with 'key'
def cache_file key
File.join( store, key+".cache" )
end
private
# creates the actual cache file
def write_cache_file key, content
f = File.open( cache_file(key), "w+" )
f.flock(File::LOCK_EX)
f.write( content )
f.close
return content
end
# reads the actual cache file
def read_cache_file key
f = File.open( cache_file(key), "r" )
f.flock(File::LOCK_SH)
out = f.read
f.close
return out
end
# returns mtime of cache file or nil if
# file doesn't exist
def read_cache_mtime key
return nil unless File.exists?(cache_file(key))
File.mtime( cache_file(key) )
end
# creates #store directory if it doesn't exist
def ensure_store_directory
Dir.mkdir( store ) unless File.directory?( store )
end
class NotFound < Exception
end
end
end
|
michaelgpearce/coinmux
|
gui/application.rb
|
<gh_stars>10-100
class Gui::Application < Java::JavaxSwing::JFrame
include Coinmux::Facades
WIDTH = 600
HEIGHT = 450
MIXES_TABLE_REFRESH_SECONDS = 5
attr_accessor :amount, :participants, :coin_join_uri, :input_private_key, :output_address, :change_address, :current_view
import 'java.awt.CardLayout'
import 'java.awt.Dimension'
import 'java.awt.Desktop'
import 'java.net.URL'
import 'java.net.URI'
import 'javax.swing.BorderFactory'
import 'javax.swing.BoxLayout'
import 'javax.swing.ImageIcon'
import 'javax.swing.JDialog'
import 'javax.swing.JFrame'
import 'javax.swing.JOptionPane'
import 'javax.swing.JPanel'
def initialize
super Coinmux::BANNER
end
def start
show_frame do
root_panel.add(card_panel)
{
available_mixes: Gui::View::AvailableMixes,
mix_settings: Gui::View::MixSettings,
mixing: Gui::View::Mixing
}.each do |key, view_class|
views[key] = view = build_view(view_class)
view.root_panel.setPreferredSize(Dimension.new(WIDTH, HEIGHT))
card_panel.add(view.root_panel, key.to_s)
view.add
end
if Coinmux.os == :macosx
Java::ComAppleEawt::Application.new.tap do |app|
app.addApplicationListener(AppleAdapter.new(self))
app.setEnabledPreferencesMenu(true)
end
end
views[:available_mixes].update
show_view(:available_mixes)
end
Gui::EventQueue.instance.future_exec(2) do # show "loading" for a couple of seconds minimum
connect_data_store
end
end
def open_webpage(url_string)
Desktop.getDesktop().browse(URL.new(url_string).toURI()) rescue puts $!
end
def show_error_dialog(*error_messages)
JOptionPane.showMessageDialog(
self,
error_messages.collect(&:to_s).to_java(:string),
"Error",
JOptionPane::ERROR_MESSAGE)
end
def show_view(view)
self.current_view = view
views[view].show
card_panel.getLayout().show(card_panel, view.to_s)
end
def root_panel
@root_panel ||= JPanel.new.tap do |panel|
panel.setLayout(BoxLayout.new(panel, BoxLayout::PAGE_AXIS))
panel.setBorder(BorderFactory.createEmptyBorder())
end
end
def preferences_panel
load_preferences_panel_and_view
@preferences_panel
end
def preferences_view
load_preferences_panel_and_view
@preferences_view
end
def data_store
@data_store ||= Coinmux::DataStore::Factory.build(coin_join_uri)
end
def show_preferences
JDialog.new(self, "Coinmux", true).tap do |dialog|
panel = JPanel.new
panel.setBorder(create_frame_border)
panel.add(preferences_panel)
dialog.add(panel)
dialog.pack
dialog.setLocationRelativeTo(self)
# show after added to dialog
preferences_view.show
dialog.show
if preferences_view.success
Coinmux::Config.instance = Coinmux::Config[preferences_view.bitcoin_network] # should get rid of singleton here
if coin_join_uri != preferences_view.coin_join_uri
if data_store.connected
data_store.disconnect
end
self.coin_join_uri = preferences_view.coin_join_uri
@data_store = nil # lazy load again
views[:available_mixes].update
connect_data_store
end
end
end
end
def show_about
icon = ImageIcon.new(Coinmux::FileUtil.read_content_as_java_bytes('gui', 'assets', 'icon_80.png'))
JOptionPane.showMessageDialog(root_panel, "Coinmux\nVersion: #{Coinmux::VERSION}", "About", JOptionPane::INFORMATION_MESSAGE, icon)
end
private
def connect_data_store
data_store.connect do |event|
if event.error
show_error_dialog("Unable to connect to data store: #{event.error}")
else
views[:available_mixes].update
refresh_mixes_table
end
end
end
def load_preferences_panel_and_view
return if @preferences_panel.present? && @preferences_view.nil?
@preferences_panel ||= JPanel.new.tap do |panel|
panel.setLayout(BoxLayout.new(panel, BoxLayout::PAGE_AXIS))
panel.setBorder(BorderFactory.createEmptyBorder())
end
@preferences_view ||= Gui::View::Preferences.new(self, @preferences_panel).tap do |preferences_view|
preferences_view.add
end
end
def update_mixes_table(coin_join_data)
views[:available_mixes].update_mixes_table(coin_join_data)
Gui::EventQueue.instance.future_exec(MIXES_TABLE_REFRESH_SECONDS) do
refresh_mixes_table # refresh again
end
end
def refresh_mixes_table
Coinmux::Application::AvailableCoinJoins.new(data_store).find do |event|
Gui::EventQueue.instance.future_exec do
if event.error
warn("Error refreshing mixes table: #{event.error}")
update_mixes_table([])
else
update_mixes_table(event.data)
end
end
end
end
def quit
Java::JavaLang::System.exit(0)
# clean_up_coin_join
end
def views
@views ||= {}
end
def card_panel
@card_panel ||= JPanel.new(CardLayout.new)
end
def build_view(view_class)
panel = JPanel.new
panel.setLayout(BoxLayout.new(panel, BoxLayout::PAGE_AXIS))
panel.setBorder(create_frame_border)
view_class.new(self, panel)
end
def create_frame_border
BorderFactory.createEmptyBorder(10, 20, 20, 20)
end
def show_frame(&block)
icon = ImageIcon.new(Coinmux::FileUtil.read_content_as_java_bytes("gui", "assets", "icon_320.png"))
setIconImage(icon.getImage())
getContentPane.add(root_panel)
setDefaultCloseOperation JFrame::EXIT_ON_CLOSE
setSize(Dimension.new(WIDTH, HEIGHT)) # even though pack() resizes, this helps start the window in the right location on screen
setLocationRelativeTo(nil)
self.coin_join_uri = preferences_view.coin_join_uri
Java::JavaLang::Runtime.getRuntime().addShutdownHook(Java::JavaLang::Thread.new do
clean_up_mixing
end)
yield
pack
setVisible(true)
root_panel.revalidate() # OSX opening with no content about 20% of time. :(
end
def clean_up_mixing
if current_view == :mixing && (mixer = views[:mixing].mixer)
Coinmux::Threading.wait_for_callback(mixer, :cancel) do
# do nothing
end
end
end
if Coinmux.os == :macosx
class AppleAdapter < Java::ComAppleEawt::ApplicationAdapter
def initialize(application)
@application = application
super()
end
def handleAbout(e)
e.setHandled(true)
@application.send(:show_about)
end
def handlePreferences(e)
@application.send(:show_preferences)
end
def handleQuit(e)
@application.send(:quit)
end
end
end
end
|
michaelgpearce/coinmux
|
spec/bitcoin_network_spec.rb
|
<gh_stars>10-100
require 'spec_helper'
describe Coinmux::BitcoinNetwork do
describe "#unspent_inputs_for_address" do
let(:data) { load_fixture("#{address}.json") }
let(:address) { 'mjcSuqvGTuq8Ys82juwa69eAb4Z69VaqEE' }
before do
http_facade.stub(:get).with(config_facade.webbtc_host, "/address/#{address}.json").and_return(data)
end
subject { bitcoin_network_facade.unspent_inputs_for_address(address) }
it "has correct unspent transaction / number and value" do
expect(subject.size).to eq(1)
expect(subject[{id: "50faf760057b52e4a9011d7989a1322b2727f5ce7f1750d5796a3883c1bf0fc7", index: 1}]).to eq(400000000)
end
end
describe "#build_unsigned_transaction" do
let(:transaction_id) { "50faf760057b52e4a9011d7989a1322b2727f5ce7f1750d5796a3883c1bf0fc7" }
let(:transaction_index) { 1 }
let(:unspent_inputs) { [{id: transaction_id, index: transaction_index}] }
let(:amount) { 400000000 }
let(:outputs) { [{ address: Helper.next_bitcoin_info[:address], amount: 100000000 }, { address: Helper.next_bitcoin_info[:address], amount: 300000000 }] }
before do
http_facade.stub(:get).with(config_facade.webbtc_host, "/tx/#{transaction_id}.bin").and_return(load_fixture("#{transaction_id}.bin"))
end
subject { Coinmux::BitcoinNetwork.instance.build_unsigned_transaction(unspent_inputs, outputs) }
context "with valid inputs" do
it "returns a transaction with inputs" do
expect(subject.getInputs().size()).to eq(1)
expect(subject.getInput(0).getOutpoint().getHash().to_s).to eq(transaction_id)
expect(subject.getInput(0).getOutpoint().getIndex()).to eq(1)
expect(subject.getInput(0).getOutpoint().getConnectedOutput().getValue().to_s.to_i).to eq(amount)
end
it "returns transaction to correct address" do
expect(subject.getOutputs().size()).to eq(outputs.size)
outputs.each_with_index do |output, index|
expect(subject.getOutput(index).value()).to eq(output[:amount])
expect(subject.getOutput(index).getScriptPubKey().getToAddress(network_params).to_s).to eq(output[:address])
end
end
end
context "with transaction that cannot be found" do
it "raises an Coinmux::Error" do
http_facade.stub(:get).with(config_facade.webbtc_host, "/tx/#{transaction_id}.bin").and_raise(Coinmux::Error.new('An http error'))
expect { subject }.to raise_error(Coinmux::Error, 'An http error')
end
end
context "with invalid transaction index" do
let(:transaction_index) { 200 }
it "raises an Coinmux::Error" do
expect { subject }.to raise_error(Coinmux::Error, 'Output index does not exist')
end
end
end
describe "#build_transaction_input_script_sig" do
let(:transaction_id) { "50faf760057b52e4a9011d7989a1322b2727f5ce7f1750d5796a3883c1bf0fc7" }
let(:transaction_index) { 1 }
let(:unspent_inputs) { [{id: transaction_id, index: transaction_index}] }
let(:amount) { 400000000 }
let(:outputs) { [{ address: Helper.next_bitcoin_info[:address], amount: 100000000 }, { address: Helper.next_bitcoin_info[:address], amount: 300000000 }] }
let(:transaction) { bitcoin_network_facade.build_unsigned_transaction(unspent_inputs, outputs) }
let(:input_index) { 0 }
let(:private_key_hex) { "FA45A0CE998DBC372DB1DD323D689A6FDBA18F5EF8D5E4453EA2454AC4EC4B10" }
before do
http_facade.stub(:get).with(config_facade.webbtc_host, "/tx/#{transaction_id}.bin").and_return(load_fixture("#{transaction_id}.bin"))
end
subject { bitcoin_network_facade.build_transaction_input_script_sig(transaction, input_index, private_key_hex) }
context "with valid inputs" do
it "creates a script_sig" do
script_sig = Java::ComGoogleBitcoinScript::Script.new(subject.unpack('c*').to_java(:byte))
tx_input = transaction.getInput(input_index)
tx_input.setScriptSig(script_sig)
expect(tx_input.verify()).to be_nil
end
end
context "with invalid private key" do
let(:private_key_hex) { "FA45A0CE998DBC372DB1DD323D689A6FDBA18F5EF8D5E4453EA2454AC4EC4B11" }
it "does not verify the input" do
script_sig = Java::ComGoogleBitcoinScript::Script.new(subject.unpack('c*').to_java(:byte))
tx_input = transaction.getInput(input_index)
tx_input.setScriptSig(script_sig)
expect { tx_input.verify() }.to raise_error(Java::ComGoogleBitcoinCore::ScriptException)
end
end
context "with invalid input index" do
let(:input_index) { 1 }
it "raises Coinmux::Error" do
expect { subject }.to raise_error(Coinmux::Error, 'Invalid input index')
end
end
end
describe "#sign_transaction_input" do
let(:transaction_id) { "50faf760057b52e4a9011d7989a1322b2727f5ce7f1750d5796a3883c1bf0fc7" }
let(:transaction_index) { 1 }
let(:unspent_inputs) { [{id: transaction_id, index: transaction_index}] }
let(:amount) { 400000000 }
let(:outputs) { [{ address: Helper.next_bitcoin_info[:address], amount: 100000000 }, { address: Helper.next_bitcoin_info[:address], amount: 300000000 }] }
let(:transaction) { bitcoin_network_facade.build_unsigned_transaction(unspent_inputs, outputs) }
let(:input_index) { 0 }
let(:private_key_hex) { "FA45A0CE998DBC372DB1DD323D689A6FDBA18F5EF8D5E4453EA2454AC4EC4B10" }
let(:script_sig) { bitcoin_network_facade.build_transaction_input_script_sig(transaction, input_index, private_key_hex) }
before do
http_facade.stub(:get).with(config_facade.webbtc_host, "/tx/#{transaction_id}.bin").and_return(load_fixture("#{transaction_id}.bin"))
end
subject { bitcoin_network_facade.sign_transaction_input(transaction, input_index, script_sig) }
context "with valid inputs" do
it "creates a script_sig" do
expect(subject).to be_nil
end
end
context "with invalid script sig" do
let(:script_sig) { "invalid-sig" }
it "creates a script_sig" do
expect { subject }.to raise_error(Coinmux::Error, /Unable to verify signature/)
end
end
context "with invalid input index" do
let(:input_index) { 1 }
it "raises Coinmux::Error" do
expect { subject }.to raise_error(Coinmux::Error, 'Invalid input index')
end
end
end
describe "#webbtc_get_json" do
let(:path) { '/a/valid/path' }
before do
http_facade.stub(:get).with(config_facade.webbtc_host, path).and_return(data)
end
subject do
bitcoin_network_facade.send(:webbtc_get_json, path)
end
context "with valid JSON" do
let(:data) { '{"key": "valid data"}' }
it "returns response as hash" do
expect(subject).to eq(JSON.parse(data))
end
end
context "with invalid JSON" do
let(:data) { 'Not JSON' }
it "raises Coinmux::Error" do
expect { subject }.to raise_error(Coinmux::Error, 'Unable to parse JSON')
end
end
context "with error JSON" do
let(:data) { '{"error": "an error"}' }
it "raises Coinmux::Error" do
expect { subject }.to raise_error(Coinmux::Error, 'Invalid request: an error')
end
end
end
describe "#post_transaction" do
let(:transaction_data) { "\x01\x02\x03" }
let(:transaction_java_bytes) { transaction_data.bytes.to_a.to_java(:byte) }
let(:transaction_hex) { transaction_data.unpack('H*').first }
let(:transaction) { double('transaction', bitcoinSerialize: transaction_java_bytes) }
before do
http_facade.stub(:post).with(config_facade.webbtc_host, "/relay_tx", tx: transaction_hex).and_return(response_content)
end
subject do
bitcoin_network_facade.send(:post_transaction, transaction)
end
context "with valid transaction data" do
let(:transaction_hash) { 'valid-hash' }
let(:response_content) { { 'hash' => transaction_hash }.to_json }
before do
http_facade.stub(:post).with(config_facade.webbtc_host, "/relay_tx", tx: transaction_hex).and_return(response_content)
end
it "returns transaction hash" do
expect(subject).to eq(transaction_hash)
end
end
context "with invalid JSON" do
let(:response_content) { 'Not JSON' }
it "raises Coinmux::Error" do
expect { subject }.to raise_error(Coinmux::Error, 'Unable to post to /relay_tx: invalid JSON response')
end
end
context "with error JSON" do
let(:response_content) { { "error" => "an error", 'detail' => 'some detail' }.to_json }
it "raises Coinmux::Error" do
expect { subject }.to raise_error(Coinmux::Error, "Unable to post to /relay_tx: an error (some detail)")
end
end
end
end
|
michaelgpearce/coinmux
|
spec/factories/messages.rb
|
FactoryGirl.define do
factory :association_message, :class => Coinmux::Message::Association do
sequence(:name) { |n| "association-#{n}" }
type :list
read_only false
data_store_identifier_from_build { Helper.data_store.generate_identifier }
data_store_identifier do
if read_only
data_store.convert_to_request_only_identifier(data_store_identifier_from_build)
else
data_store_identifier_from_build
end
end
data_store { Helper.data_store }
end
factory :coin_join_message, :class => Coinmux::Message::CoinJoin do
ignore do
template_message { Coinmux::Message::CoinJoin.build(Helper.data_store) }
end
version { template_message.version }
identifier { template_message.identifier }
message_private_key { template_message.message_private_key }
message_public_key { template_message.message_public_key }
amount { 100_000_000 }
participants { 2 }
participant_transaction_fee { template_message.participant_transaction_fee }
data_store { Helper.data_store }
inputs { association :association_message, strategy: :build, data_store: Helper.data_store, name: 'input', type: :list, read_only: false, created_with_build: true }
outputs { association :association_message, strategy: :build, data_store: Helper.data_store, name: 'output', type: :list, read_only: false, created_with_build: true }
message_verification { association :association_message, strategy: :build, data_store: Helper.data_store, name: 'message_verification', type: :fixed, read_only: true, created_with_build: true }
transaction { association :association_message, strategy: :build, data_store: Helper.data_store, name: 'transaction', type: :fixed, read_only: true, created_with_build: true }
transaction_signatures { association :association_message, strategy: :build, data_store: Helper.data_store, name: 'transaction_signature', type: :list, read_only: false, created_with_build: true }
status { association :association_message, strategy: :build, data_store: Helper.data_store, name: 'status', type: :variable, read_only: true, created_with_build: true }
#
# NOTE: traits ordering is important and should probably be loaded in the order defined below
#
trait :with_inputs do
after(:build) do |coin_join|
[true, false].each do |created_with_build|
bitcoin_info = Helper.next_bitcoin_info
message_keys = pki_facade.generate_keypair
coin_join.inputs.insert(FactoryGirl.build(:input_message,
address: bitcoin_info[:address],
private_key: bitcoin_info[:private_key],
signature: bitcoin_crypto_facade.sign_message!(coin_join.identifier, bitcoin_info[:private_key]),
change_address: Helper.next_bitcoin_info[:address],
change_transaction_output_identifier: rand.to_s,
message_private_key: message_keys.first,
message_public_key: message_keys.last,
created_with_build: created_with_build,
coin_join: coin_join))
end
end
end
trait :with_message_verification do
after(:build) do |coin_join|
coin_join.message_verification.insert(FactoryGirl.build(:message_verification_message, :coin_join => coin_join, :created_with_build => true))
end
end
trait :with_outputs do
after(:build) do |coin_join|
coin_join.outputs.insert(FactoryGirl.build(:output_message, :coin_join => coin_join, :created_with_build => true))
coin_join.outputs.insert(FactoryGirl.build(:output_message, :coin_join => coin_join, :created_with_build => false))
end
end
trait :with_transaction do
after(:build) do |coin_join|
inputs = coin_join.inputs.value.collect do |input|
{ 'address' => input.address, 'transaction_id' => "tx-#{input.address}", 'output_index' => 123 }
end
outputs = coin_join.outputs.value.each_with_index.collect do |output|
{ 'address' => output.address, 'amount' => coin_join.amount, 'identifier' => output.transaction_output_identifier }
end
outputs += coin_join.inputs.value.each_with_index.collect do |input|
{ 'address' => input.change_address, 'amount' => rand(1..4) * Coinmux::BitcoinUtil::SATOSHIS_PER_BITCOIN - coin_join.participant_transaction_fee, 'identifier' => input.change_transaction_output_identifier }
end
coin_join.transaction.insert(FactoryGirl.build(:transaction_message, :coin_join => coin_join, :inputs => inputs, :outputs => outputs))
end
end
trait :with_transaction_signatures do
after(:build) do |coin_join|
coin_join.transaction.value.inputs.each_with_index do |input_hash, index|
script_sig = "scriptsig-#{index}"
message_verification = coin_join.build_message_verification(:transaction_signature, index, script_sig)
coin_join.transaction_signatures.insert(FactoryGirl.build(:transaction_signature_message, coin_join: coin_join, transaction_input_index: index, script_sig: Base64.encode64(script_sig), message_verification: message_verification))
end
end
end
end
factory :input_message, :class => Coinmux::Message::Input do
ignore do
template_message { FactoryGirl.build(:coin_join_message, :with_inputs).inputs.value.detect(&:created_with_build) }
end
address { template_message.address }
private_key { template_message.private_key }
signature { template_message.signature }
change_address { template_message.change_address }
change_transaction_output_identifier { template_message.change_transaction_output_identifier }
message_private_key { template_message.message_private_key }
message_public_key { template_message.message_public_key }
coin_join { template_message.coin_join }
end
factory :output_message, :class => Coinmux::Message::Output do
ignore do
bitcoin_info { Helper.next_bitcoin_info }
end
address { bitcoin_info[:address] }
transaction_output_identifier { rand.to_s }
coin_join { association :coin_join_message, strategy: :build, identifier: bitcoin_info[:identifier] }
after(:build) do |output|
output.message_verification = output.build_message_verification
end
end
factory :status_message, :class => Coinmux::Message::Status do
state "completed"
transaction_id { "valid_transaction_id:#{rand}" }
association :coin_join, factory: :coin_join_message, strategy: :build
end
factory :message_verification_message, :class => Coinmux::Message::MessageVerification do
ignore do
template_message { Coinmux::Message::MessageVerification.build(Coinmux::Message::CoinJoin.build(Helper.data_store)) }
end
message_identifier { template_message.message_identifier }
secret_key { template_message.secret_key }
encrypted_message_identifier { template_message.encrypted_message_identifier }
coin_join { association :coin_join_message, :with_inputs, strategy: :build }
after(:build) do |message_verification|
message_verification.encrypted_secret_keys = message_verification.build_encrypted_secret_keys
end
end
factory :transaction_message, :class => Coinmux::Message::Transaction do
ignore do
template_message { FactoryGirl.build(:coin_join_message, :with_inputs, :with_message_verification, :with_outputs, :with_transaction).transaction.value }
end
inputs { template_message.inputs }
outputs { template_message.outputs }
coin_join { template_message.coin_join }
end
factory :transaction_signature_message, :class => Coinmux::Message::TransactionSignature do
ignore do
template_message { FactoryGirl.build(:coin_join_message, :with_inputs, :with_message_verification, :with_outputs, :with_transaction, :with_transaction_signatures).transaction_signatures.value.first }
end
transaction_input_index { template_message.transaction_input_index }
script_sig { template_message.script_sig }
message_verification { template_message.message_verification }
coin_join { template_message.coin_join }
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/inflections.rb
|
class String
def humanize
gsub(/_/, ' ')
end
def classify
singularize.gsub(/_/, ' ').split(' ').collect(&:capitalize).join
end
def singularize
if match /uses$/
self[0...-2]
elsif match /es$/
self[0...-1]
elsif match /[^us]s$/
self[0...-1]
else
self
end
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/logger.rb
|
require 'logger'
class Coinmux::Logger
include Singleton
def debug(*messages)
write_messages(:debug, messages)
end
def info(*messages)
write_messages(:info, messages)
end
def warn(*messages)
write_messages(:warn, messages)
end
def error(*messages)
write_messages(:error, messages)
end
def fatal(*messages)
write_messages(:fatal, messages)
end
def level=(level)
@level = logger.level = level.is_a?(Fixnum) ? level : ::Logger.const_get(level.to_s.upcase)
end
def level
@level
end
def logger
return @logger if @logger
path = Coinmux::FileUtil.root_mkdir_p('log')
file = File.open(File.join(path, "coinmux-#{Coinmux.env}.log"), 'a')
file.sync = true
@logger = ::Logger.new(file, 1)
end
private
def write_messages(method, messages)
messages.each { |message| logger.send(method, message) }
nil
end
end
|
michaelgpearce/coinmux
|
lib/coinmux.rb
|
$:.unshift(File.expand_path("../..", __FILE__))
require 'json'
require 'singleton'
require 'base64'
require 'set'
Dir[File.join(File.dirname(__FILE__), 'jar', '*.jar')].each { |filename| require filename }
module Coinmux
require 'rbconfig'
module Application; end
module Message; end
module StateMachine; end
module DataStore; end
def self.root
@root ||= File.expand_path(File.join(File.dirname(__FILE__), '..'))
end
def self.env
ENV['COINMUX_ENV'] || 'development'
end
def self.os
@os ||= (
host_os = RbConfig::CONFIG['host_os']
case host_os
when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
:windows
when /darwin|mac os/
:macosx
when /linux/
:linux
when /solaris|bsd/
:unix
else
raise Error::WebDriverError, "unknown os: #{host_os.inspect}"
end
)
end
end
require 'lib/coinmux/try'
require 'lib/coinmux/assert_keys'
require 'lib/coinmux/blank_and_present'
require 'lib/coinmux/inflections'
require 'lib/coinmux/validation_model'
require 'lib/coinmux/proper'
require 'lib/coinmux/file_util'
require 'lib/coinmux/threading'
require 'lib/coinmux/version'
require 'lib/coinmux/facades'
require 'lib/coinmux/http'
require 'lib/coinmux/coin_join_uri'
require 'lib/coinmux/error'
require 'lib/coinmux/digest'
require 'lib/coinmux/cipher'
require 'lib/coinmux/pki'
require 'lib/coinmux/bitcoin_util'
require 'lib/coinmux/bitcoin_crypto'
require 'lib/coinmux/bitcoin_network'
require 'lib/coinmux/event'
require 'lib/coinmux/config'
require 'lib/coinmux/logger'
require 'lib/coinmux/data_store/base'
require 'lib/coinmux/data_store/tomp2p'
require 'lib/coinmux/data_store/memory'
require 'lib/coinmux/data_store/file'
require 'lib/coinmux/data_store/factory'
require 'lib/coinmux/message/base'
require 'lib/coinmux/message/association'
require 'lib/coinmux/message/coin_join'
require 'lib/coinmux/message/status'
require 'lib/coinmux/message/input'
require 'lib/coinmux/message/message_verification'
require 'lib/coinmux/message/output'
require 'lib/coinmux/message/transaction'
require 'lib/coinmux/message/transaction_signature'
require 'lib/coinmux/state_machine/event'
require 'lib/coinmux/state_machine/base'
require 'lib/coinmux/state_machine/director'
require 'lib/coinmux/state_machine/participant'
require 'lib/coinmux/application/available_coin_joins'
require 'lib/coinmux/application/input_validator'
require 'lib/coinmux/application/mixer'
|
michaelgpearce/coinmux
|
lib/coinmux/message/message_verification.rb
|
class Coinmux::Message::MessageVerification < Coinmux::Message::Base
property :encrypted_message_identifier
property :encrypted_secret_keys
attr_accessor :message_identifier, :secret_key
validates :encrypted_message_identifier, :encrypted_secret_keys, :presence => true
validates :message_identifier, :secret_key, :presence => true, :if => :created_with_build?
validates :message_identifier, :secret_key, :absence => true, :unless => :created_with_build?
validate :ensure_has_addresses_for_all_encrypted_secret_keys, :unless => :created_with_build?
validate :ensure_owned_input_can_decrypt_message_identifier, :unless => :created_with_build?
validate :ensure_encrypted_secret_keys_size_is_participant_count
class << self
def build(coin_join)
message = super(coin_join.data_store, coin_join)
message.message_identifier = digest_facade.random_identifier
message.secret_key = digest_facade.random_identifier
message.encrypted_message_identifier = Base64.encode64(cipher_facade.encrypt(message.secret_key, message.message_identifier)).strip
message.encrypted_secret_keys = message.build_encrypted_secret_keys
message
end
end
def build_encrypted_secret_keys
# only selected inputs will get the secret to decrypt the identifier
coin_join.inputs.value.inject({}) do |acc, input|
encrypted_secret_key = pki_facade.public_encrypt(input.message_public_key, secret_key)
acc[input.address] = Base64.encode64(encrypted_secret_key)
acc
end
end
# raise ArgumentError if unable to decrypt
def get_secret_key_for_address!(address)
input = coin_join.inputs.value.detect { |input| input.address.to_s == address.to_s }
raise "Invalid state: no input!" if input.nil?
encoded_encrypted_secret_key = encrypted_secret_keys[address]
raise ArgumentError, "not found for address #{address}" if encoded_encrypted_secret_key.nil?
encrypted_secret_key = (Base64.decode64(encoded_encrypted_secret_key) rescue nil) || ""
secret_key = pki_facade.private_decrypt(input.message_private_key, encrypted_secret_key) rescue nil
raise ArgumentError, "cannot be decrypted" if secret_key.nil?
secret_key
end
private
def ensure_encrypted_secret_keys_size_is_participant_count
return unless errors[:encrypted_secret_keys].empty?
(errors[:encrypted_secret_keys] << "does not match number of participants" and return) unless encrypted_secret_keys.size == coin_join.participants
end
def ensure_owned_input_can_decrypt_message_identifier
input = coin_join.inputs.value.detect(&:message_private_key)
raise "Invalid state: no input!" if input.nil?
get_secret_key_for_address!(input.address)
rescue ArgumentError => e
errors[:encrypted_secret_keys] << e.message
end
def ensure_has_addresses_for_all_encrypted_secret_keys
(errors[:encrypted_secret_keys] << "is not a Hash" and return) unless encrypted_secret_keys.is_a?(Hash)
errors[:encrypted_secret_keys] << "contains address not an input" if (encrypted_secret_keys.keys.collect(&:to_s) - coin_join.inputs.value.collect(&:address)).size != 0
end
end
|
michaelgpearce/coinmux
|
cli/application.rb
|
<gh_stars>10-100
class Cli::Application
include Coinmux::BitcoinUtil, Coinmux::Facades
attr_accessor :participant, :director
attr_accessor :amount, :participants, :input_private_key, :output_address, :change_address, :coin_join_uri
def initialize(options = {})
options.assert_keys!(required: [:amount, :participants, :input_private_key, :output_address, :change_address], optional: [:data_store, :list])
self.amount = (options[:amount].to_f * SATOSHIS_PER_BITCOIN).to_i
self.participants = options[:participants].to_i
self.input_private_key = options[:input_private_key]
self.output_address = options[:output_address]
self.change_address = options[:change_address]
self.coin_join_uri = if options[:data_store]
"coinjoin://coinmux/#{options[:data_store]}"
else
Coinmux::Config.instance.coin_join_uri
end
end
def list_coin_joins
data_store.connect
run_list_coin_joins
data_store.disconnect
end
def start
if self.input_private_key.blank?
puts "Enter your private key:"
self.input_private_key = input_password
end
input_validator = Coinmux::Application::InputValidator.new(
data_store: data_store,
coin_join_uri: coin_join_uri,
input_private_key: input_private_key,
amount: amount,
participants: participants,
change_address: change_address,
output_address: output_address)
if (input_errors = input_validator.validate).present?
message "Unable to perform CoinJoin due to the following:"
message input_errors.collect { |message| " * #{message}" }
message "Quitting..."
return
end
# ensure we have the key in hex
self.input_private_key = bitcoin_crypto_facade.private_key_to_hex!(input_private_key)
message "Starting..."
data_store.connect
Cli::EventQueue.instance.start
Kernel.trap('SIGINT') { clean_up_coin_join }
Kernel.trap('SIGTERM') { clean_up_coin_join }
mixer.start do |event|
if event.source == :mixer && event.type == :done
Cli::EventQueue.instance.stop
else
message = event.options[:message]
if event.type == :failed
message "Error - #{message}", event.source
message "Quitting..."
else
message "#{event.type.to_s.humanize.capitalize}#{" - #{message}" if message}", event.source
if event.source == :participant && event.type == :completed
message "CoinJoin successfully created!"
end
end
end
end
Cli::EventQueue.instance.wait
data_store.disconnect
end
private
def mixer
@mixer ||= build_mixer
end
def build_mixer
Coinmux::Application::Mixer.new(
event_queue: Cli::EventQueue.instance,
data_store: data_store,
amount: amount,
participants: participants,
input_private_key: input_private_key,
output_address: output_address,
change_address: change_address)
end
def clean_up_coin_join
if mixer
message "Canceling..."
mixer.cancel do
Cli::EventQueue.instance.stop
end
end
end
def run_list_coin_joins
begin
available_coin_joins = Coinmux::Application::AvailableCoinJoins.new(data_store).find
if available_coin_joins.empty?
puts "No available CoinJoins"
else
puts "%10s %12s" % ["BTC Amount", "Participants"]
puts "#{'=' * 10} #{'=' * 12}"
available_coin_joins.each do |hash|
puts "%-10s %-12s" % [hash[:amount].to_f / SATOSHIS_PER_BITCOIN, "#{hash[:waiting_participants]} of #{hash[:total_participants]}"]
end
end
rescue Coinmux::Error => e
puts "Error: #{e}"
end
end
def message(messages, event_type = nil)
messages = [messages] unless messages.is_a?(Array)
messages.each do |message|
message = "%14s %s" % ['[' + event_type.to_s.capitalize + ']:', message] if event_type
puts message
info message
end
end
def data_store
@data_store ||= Coinmux::DataStore::Factory.build(Coinmux::CoinJoinUri.parse(coin_join_uri))
end
def input_password
line = if PLATFORM == 'java'
import 'jline.console.ConsoleReader'
Java::jlineConsole::ConsoleReader.new().readLine(Java::JavaLang::Character.new('*'.bytes.first))
else
STDIN.noecho(&:gets)
end
line.strip
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/message/base.rb
|
<filename>lib/coinmux/message/base.rb
class Coinmux::Message::Base
include Coinmux::ValidationModel, Coinmux::Facades, Coinmux::Proper
MAX_JSON_DATA_SIZE = 10_000 # not sure the best number for this, but all our messages should be small
ASSOCIATION_TYPES = [:list, :fixed, :variable]
attr_accessor :coin_join, :created_with_build, :data_store
validate :coin_join_valid, :if => :should_validate_coin_join
class << self
def build(data_store, coin_join = nil)
message = build_without_associations(data_store, coin_join)
coin_join = message if self == Coinmux::Message::CoinJoin
associations.each do |name, config|
message[name] = Coinmux::Message::Association.build(coin_join, name: name, type: config[:type], read_only: config[:read_only])
end
message
end
def from_json(json, data_store, coin_join = nil)
return nil if json.nil?
return nil if json.bytesize > MAX_JSON_DATA_SIZE
hash = JSON.parse(json) rescue nil
return nil unless hash.is_a?(Hash)
from_hash(hash, data_store, coin_join)
end
def from_hash(hash, data_store, coin_join = nil)
return nil unless self.properties.collect(&:to_s).sort == hash.keys.sort
message = self.new
message.data_store = data_store
coin_join = message if self == Coinmux::Message::CoinJoin
message.coin_join = coin_join
hash.each do |property_name, value|
property = property_name.to_sym
if associations[property]
association = association_from_data_store_identifier(coin_join, property, value)
return nil if association.nil?
message[property] = association
else
message[property] = value
end
end
if !message.valid?
debug "Message #{self} is not valid: #{hash}, #{message.errors.full_messages}"
return nil
end
message
end
def add_association(name, type, options)
options.assert_keys!(required: :read_only)
raise ArgumentError, "Invalid association type: #{type}" unless ASSOCIATION_TYPES.include?(type)
property(name)
associations[name] = options.merge(:type => type)
end
def associations
@associations ||= {}
end
protected
def build_without_associations(data_store, coin_join)
message = new
message.data_store = data_store
message.coin_join = coin_join
message.created_with_build = true
message
end
private
def association_from_data_store_identifier(coin_join, property, identifier)
config = associations[property]
Coinmux::Message::Association.from_data_store_identifier(identifier, coin_join, property, config[:type], config[:read_only])
end
end
def initialize(attributes = {})
self.created_with_build = false
attributes.each do |key, value|
send("#{key}=", value)
end
end
def director?
coin_join.director?
end
def created_with_build?
!!created_with_build
end
def to_hash
self.class.associations.keys.reduce(super) do |acc, property|
acc[property.to_s] = self[property].data_store_identifier
acc
end
end
private
def should_validate_coin_join
!is_a?(Coinmux::Message::CoinJoin) && !is_a?(Coinmux::Message::Association)
end
def coin_join_valid
return if coin_join == self
errors[:coin_join] << "is not valid" unless coin_join.valid?
end
end
|
michaelgpearce/coinmux
|
gui/view/mix_settings.rb
|
<filename>gui/view/mix_settings.rb
class Gui::View::MixSettings < Gui::View::Base
DEFAULT_PARTICIPANTS = 5
DEFAULT_AMOUNT = 1.0 * SATOSHIS_PER_BITCOIN
MAX_PARTICIPANTS = 100
import 'java.awt.Component'
import 'java.awt.Dimension'
import 'java.awt.Insets'
import 'javax.swing.JButton'
import 'javax.swing.JLabel'
import 'javax.swing.JOptionPane'
import 'javax.swing.JPanel'
import 'javax.swing.JPasswordField'
import 'javax.swing.JSpinner'
import 'javax.swing.JTextField'
import 'javax.swing.SpinnerModel'
import 'javax.swing.SpinnerNumberModel'
import 'javax.swing.SwingWorker'
protected
def handle_add
add_header("Mix Settings")
add_form_row("Bitcoin Amount (BTC)", amount, 0, width: 100, tool_tip: "Bitcoin amount mixed with other participants and sent to the output address")
add_form_row("Number of Participants", participants, 1, width: 100, tool_tip: "More participants adds security, but will take more time to complete")
add_form_row("Input Private Key", input_private_key, 2, tool_tip: "See your wallet software's documentation for exporting private keys")
add_form_row("Output Address", output_address, 3, tool_tip: "Mixed bitcoin amount will be sent to this address")
add_form_row("Change Address", change_address, 4, tool_tip: "Un-mixed funds in your wallet sent to this address", last: true)
add_button_row(start_button, cancel_button)
end
def handle_show
bitcoin_amount = (application.amount || DEFAULT_AMOUNT).to_f / SATOSHIS_PER_BITCOIN
amount.setText(bitcoin_amount.to_s)
amount.setEnabled(application.amount.nil?)
participants.setValue(application.participants || DEFAULT_PARTICIPANTS)
participants.setEnabled(application.participants.nil?)
input_private_key.setText("")
output_address.setText("")
change_address.setText("")
end
private
class ValidationWorker < SwingWorker
include Coinmux::BitcoinUtil, Coinmux::Facades
attr_accessor :mix_settings, :input_errors
def initialize(mix_settings)
super()
self.mix_settings = mix_settings
end
def doInBackground
begin
input_validator = Coinmux::Application::InputValidator.new(
data_store: data_store,
amount: amount,
participants: participants,
input_private_key: input_private_key,
change_address: change_address,
output_address: output_address)
self.input_errors = input_validator.validate
rescue Exception => e
error "Error in ValidationWorker: #{e}"
puts "Error in ValidationWorker: #{e}", e.backtrace
raise e
end
end
def done
mix_settings.send(:start_button).setEnabled(true)
mix_settings.send(:start_button).setLabel("Start Mixing")
if input_errors.present?
mix_settings.application.show_error_dialog(*input_errors)
else
mix_settings.application.tap do |app|
app.amount = amount
app.participants = participants
app.input_private_key = bitcoin_crypto_facade.private_key_to_hex!(input_private_key)
app.output_address = output_address
app.change_address = change_address
app.show_view(:mixing)
end
end
end
private
def data_store
mix_settings.application.data_store
end
def amount
(mix_settings.send(:amount).getText().to_f * SATOSHIS_PER_BITCOIN).to_i
end
def participants
mix_settings.send(:participants).getValue()
end
def input_private_key
mix_settings.send(:input_private_key).getText()
end
def change_address
mix_settings.send(:change_address).getText()
end
def output_address
mix_settings.send(:output_address).getText()
end
end
def change_address
@change_address ||= JTextField.new
end
def output_address
@output_address ||= JTextField.new
end
def input_private_key
@input_private_key ||= JPasswordField.new
end
def start_button
@start_button ||= JButton.new("Start Mixing").tap do |start_button|
start_button.setPreferredSize(Dimension.new(120, start_button.getPreferredSize().height)) # size that accomodates both labels
start_button.add_action_listener do |e|
start_button.setEnabled(false)
start_button.setLabel("Validating...")
ValidationWorker.new(self).execute()
end
end
end
def cancel_button
@cancel_button ||= JButton.new("Back").tap do |cancel_button|
cancel_button.add_action_listener do |e|
application.show_view(:available_mixes)
end
end
end
def amount
@amount ||= JTextField.new
end
def participants
@participants ||= JSpinner.new(build_spinner_model).tap do |participants|
if participants.getEditor().respond_to?(:getTextField)
participants.getEditor().getTextField().setHorizontalAlignment(JTextField::LEFT)
end
participants.setValue(DEFAULT_PARTICIPANTS)
end
end
def build_spinner_model
spinner_model_constructor = SpinnerNumberModel.java_class.constructor(Java::int, Java::int, Java::int, Java::int)
spinner_model_constructor.new_instance(DEFAULT_PARTICIPANTS, 2, MAX_PARTICIPANTS, 1)
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/state_machine/base.rb
|
<reponame>michaelgpearce/coinmux
class Coinmux::StateMachine::Base
include Coinmux::Facades
MESSAGE_POLL_INTERVAL = 5
attr_accessor :event_queue, :coin_join_message, :notification_callback, :state, :amount, :participants, :data_store
def initialize(options = {})
super() # NOTE: This *must* be called, otherwise states won't get initialized
self.event_queue = options[:event_queue]
self.data_store = options[:data_store]
coin_join_message = Coinmux::Message::CoinJoin.build(options[:data_store], amount: options[:amount], participants: options[:participants])
raise ArgumentError, "Input params should have been validated! #{self.coin_join_message.errors.full_messages}" if !coin_join_message.valid?
self.amount = options[:amount]
self.participants = options[:participants]
end
protected
def assert_initialize_params!(params, options = {})
params.assert_keys!(
required: [:event_queue, :amount, :participants, :data_store] + (options[:required] || []),
optional: options[:optional])
end
def source
self.class.name.gsub(/.*::/, '').downcase.to_sym
end
def notify(type, options = {})
info "notify: #{source} #{type} #{options}"
event = Coinmux::StateMachine::Event.new(source: source, type: type, options: options)
event_queue.sync_exec do
notification_callback.call(event)
end
end
def failure(error_identifier, error_message = nil)
raise NotImplementedError
end
def insert_message(association, message, coin_join = coin_join_message, &callback)
coin_join.send(association).insert(message) do |event|
handle_event(event, :"unable_to_insert_into_#{association}") do
yield
end
end
end
def refresh_message(association, coin_join = coin_join_message, &callback)
coin_join.send(association).refresh do |event|
handle_event(event, :"unable_to_refresh_#{association}") do
yield
end
end
end
def handle_event(event, error_identifier, &callback)
if event.error
failure(error_identifier, event.error)
else
yield
end
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/data_store/factory.rb
|
class Coinmux::DataStore::Factory
NETWORK_TO_CLASS = {
p2p: 'Tomp2p',
filesystem: 'File',
test: 'Memory'
}
class << self
def build(coin_join_uri)
data_store_class_name = NETWORK_TO_CLASS[coin_join_uri.network.to_sym]
Coinmux::DataStore.const_get(data_store_class_name).new(coin_join_uri)
end
end
end
|
michaelgpearce/coinmux
|
spec/message/transaction_spec.rb
|
require 'spec_helper'
describe Coinmux::Message::Transaction do
let(:template_message) { build(:transaction_message) }
let(:coin_join) { template_message.coin_join }
let(:inputs) { template_message.inputs }
let(:outputs) { template_message.outputs }
before do
stub_bitcoin_network_for_coin_join(coin_join)
end
describe "validations" do
let(:message) do
build(:transaction_message,
inputs: inputs,
outputs: outputs,
coin_join: coin_join)
end
subject { message.valid? }
it "is valid with default data" do
expect(subject).to be_true
end
describe "#inputs_is_array_of_hashes" do
context "with non-array" do
let(:inputs) { 'not an array' }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:inputs]).to include("is not an array")
end
end
context "with non-hash array element" do
let(:inputs) { ['not a hash'] }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:inputs]).to include("is not a hash")
end
end
end
describe "#inputs_is_array_of_hashes" do
context "with non-array" do
let(:outputs) { 'not an array' }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("is not an array")
end
end
context "with non-hash array element" do
let(:outputs) { ['not a hash'] }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("is not a hash")
end
end
end
describe "#has_minimum_number_of_coin_join_amount_outputs" do
let(:removed_output) { template_message.outputs.detect { |output| output['amount'] == coin_join.amount } }
let(:outputs) { template_message.outputs.select { |output| output != removed_output } }
it "is invalid with missing output" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("does not have enough participants")
end
end
describe "#has_no_duplicate_inputs" do
let(:inputs) { template_message.inputs + [template_message.inputs.first] }
it "is invalid with duplicate inputs" do
expect(subject).to be_false
expect(message.errors[:inputs]).to include("has a duplicate input")
end
end
describe "#has_no_duplicate_outputs" do
context "with duplicate outputs" do
let(:outputs) { template_message.outputs + [template_message.outputs.first.dup] }
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("has a duplicate output")
end
context "with different identifiers" do
before do
outputs.last['identifier'] = "A different identifier: #{rand.to_s}"
end
it "is valid" do
expect(subject).to be_true
end
end
end
end
describe "#has_correct_participant_inputs" do
let(:removed_input_tx) { template_message.participant_input_transactions.first }
let(:inputs) { template_message.inputs.select { |input| input['transaction_id'] != removed_input_tx[:id] } }
it "is invalid with missing input" do
expect(subject).to be_false
expect(message.errors[:inputs]).to include("does not contain transaction #{removed_input_tx[:id]}:#{removed_input_tx[:index]}")
end
end
describe "#has_correct_participant_outputs" do
let(:participant_output) { template_message.participant_output }
let(:participant_output_address) { participant_output.address }
let(:participant_transaction_output_identifier) { participant_output.transaction_output_identifier }
let(:participant_input) { template_message.participant_input }
let(:participant_change_address) { participant_input.change_address }
let(:participant_change_transaction_output_identifier) { participant_input.change_transaction_output_identifier }
let(:participant_output_hash) { outputs.detect { |output| output['address'] == participant_output_address } }
let(:participant_change_hash) { outputs.detect { |output| output['address'] == participant_change_address } }
context "with incorrect participant coin_join output amount" do
before do
participant_output_hash['amount'] = coin_join.amount - 1
participant_change_hash['amount'] = coin_join.amount # so we have the correct number of coin_join.amount outputs
end
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("does not have output to #{participant_output_address} for #{coin_join.amount}")
end
end
context "with incorrect transaction output identifier" do
before do
participant_output.transaction_output_identifier = 'a different identifier'
end
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("does not have output to #{participant_output_address} for #{coin_join.amount}")
end
end
context "with change amount but no change address" do
before do
participant_input.change_address = nil
end
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("has no change address for amount #{message.participant_change_amount}")
end
end
context "with incorrect change transaction output identifier" do
before do
participant_input.change_transaction_output_identifier = 'a different identifier'
end
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("does not have output to #{message.participant_input.change_address} for #{message.participant_change_amount}")
end
end
context "with incorrect participant change output amount" do
before do
participant_change_hash['amount'] = 1
end
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:outputs]).to include("does not have output to #{message.participant_input.change_address} for #{message.participant_change_amount}")
end
end
end
end
describe "#build" do
subject { Coinmux::Message::Transaction.build(coin_join, inputs: inputs, outputs: outputs) }
it "builds valid transaction" do
expect(subject.valid?).to be_true
end
end
describe "#from_json" do
let(:message) { template_message }
let(:json) do
{
inputs: message.inputs,
outputs: message.outputs
}.to_json
end
subject do
Coinmux::Message::Transaction.from_json(json, data_store, coin_join)
end
it "creates a valid transaction" do
expect(subject).to_not be_nil
expect(subject.valid?).to be_true
expect(subject.inputs).to eq(message.inputs)
expect(subject.outputs).to eq(message.outputs)
end
end
end
|
michaelgpearce/coinmux
|
gui/view/preferences.rb
|
class Gui::View::Preferences < Gui::View::Base
NETWORK_CONFIG_KEYS = %w(mainnet testnet)
NETWORK_CONFIG_KEYS.reverse! if Coinmux.env == 'development' # first element will be default
DATA_STORE_NAME_MAP = {
'P2P' => 'p2p',
'Filesystem' => 'filesystem'
} # first element will be default
NETWORK_NAME_MAP = NETWORK_CONFIG_KEYS.each_with_object({}) do |network_key, map|
map[Coinmux::Config[network_key].name] = network_key
end
attr_accessor :success
import 'java.awt.Dimension'
import 'java.awt.GridLayout'
import 'javax.swing.BorderFactory'
import 'javax.swing.JButton'
import 'javax.swing.JComboBox'
import 'javax.swing.JScrollPane'
import 'javax.swing.JTable'
import 'javax.swing.SwingUtilities'
import 'javax.swing.border.TitledBorder'
import 'javax.swing.table.AbstractTableModel'
import 'javax.swing.table.TableModel'
def coin_join_uri
Coinmux::CoinJoinUri.new(network: selected_data_store_key, params: selected_table_model_params)
end
def bitcoin_network
selected_network_key
end
def add
add_header("Preferences")
add_form_row("Bitcoin Network", network_combo_box, 0, label_width: 140, tool_tip: "Mainnet is the standard Bitcoin network")
add_form_row("Data Store", data_store_combo_box, 1, label_width: 140, tool_tip: "P2P mixes your bitcoins other Coinmux users on the Internet")
add_row do |parent|
JPanel.new(GridLayout.new(1, 1)).tap do |panel|
scroll_pane = JScrollPane.new(data_store_properties_table)
scroll_pane.setPreferredSize(Dimension.new(200, 100))
panel.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEmptyBorder(), "Data Store Properties", TitledBorder::LEFT, TitledBorder::TOP))
panel.add(scroll_pane)
parent.add(panel, build_grid_bag_constraints(gridy: 2, fill: :both, anchor: :center, weighty: 1000000))
end
end
add_button_row(save_button, cancel_button)
end
protected
def handle_show
self.success = false
save_button.setEnabled(application.current_view == :available_mixes)
end
private
def close_preferences(success)
self.success = success
SwingUtilities.getWindowAncestor(root_panel).dispose
end
def network_combo_box
@network_combo_box ||= JComboBox.new(NETWORK_NAME_MAP.keys.to_java(:string)).tap do |combo_box|
combo_box.setVisible(Coinmux.env != 'production')
combo_box.addActionListener() do |e|
data_store_properties_table.setModel(selected_table_model)
end
end
end
def data_store_combo_box
@data_store_combo_box ||= JComboBox.new(DATA_STORE_NAME_MAP.keys.to_java(:string)).tap do |combo_box|
combo_box.addActionListener() do |e|
data_store_properties_table.setModel(selected_table_model)
end
end
end
def data_store_properties_table
@data_store_properties_table ||= JTable.new(selected_table_model)
end
def data_store_properties_model
model = data_store_properties_table.getModel()
model.getRowCount().times.each_with_object({}) do |row, params|
value = model.getValueAt(row, 1)
params[model.getValueAt(row, 0)] = value if value.present?
end
end
def save_button
@save_button ||= JButton.new("Save").tap do |save_button|
save_button.addActionListener() do |e|
close_preferences(true)
end
end
end
def cancel_button
@cancel_button ||= JButton.new("Cancel").tap do |cancel_button|
cancel_button.addActionListener() do |e|
close_preferences(false)
end
end
end
def table_models
@table_models ||= NETWORK_CONFIG_KEYS.each_with_object({}) do |network_key, network_key_map|
network_key_map[network_key] = DATA_STORE_NAME_MAP.values.each_with_object({}) do |data_store_key, data_store_key_map|
coin_join_params = Coinmux::CoinJoinUri.parse(Coinmux::Config[network_key].coin_join_uris[data_store_key]).params
data_store_key_map[data_store_key] = TModel.new(coin_join_params)
end
end
end
def selected_network_key
NETWORK_NAME_MAP[network_combo_box.getSelectedItem().to_s]
end
def selected_data_store_key
DATA_STORE_NAME_MAP[data_store_combo_box.getSelectedItem().to_s]
end
def selected_table_model
table_model(selected_network_key, selected_data_store_key)
end
def selected_table_model_params
selected_table_model.data.each_with_object({}) do |row, result|
result[row[0].strip] = row[1].strip if row[0].try(:strip).present?
end
end
def table_model(network_key, data_store_key)
table_models[network_key][data_store_key]
end
class TModel < AbstractTableModel
COLS = 2
ROWS = 5
attr_accessor :data
def initialize(coin_join_params)
super()
self.data = Array.new(ROWS) { Array.new(COLS) }
coin_join_params.each_with_index do |(key, value), index|
data[index][0] = key
data[index][1] = value
end
end
def getColumnCount(); COLS; end
def getRowCount(); data.size; end
def isCellEditable(row, col); true; end
def getColumnClass(col); Java::JavaLang::String; end
def getColumnName(index); %w(Name Value)[index]; end
def setValueAt(value, row, col); data[row][col] = value; end
def getValueAt(row, col); data[row][col]; end
end
end
|
michaelgpearce/coinmux
|
cli/event.rb
|
class Cli::Event
attr_accessor :callback, :invoke_at, :interval_period, :interval_identifier, :mutex, :condition_variable
def initialize(attrs = {})
attrs.each { |k, v| send("#{k}=", v) }
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/error.rb
|
<gh_stars>10-100
class Coinmux::Error < StandardError
end
|
michaelgpearce/coinmux
|
lib/coinmux/data_store/tomp2p.rb
|
<filename>lib/coinmux/data_store/tomp2p.rb
require 'java'
class Coinmux::DataStore::Tomp2p < Coinmux::DataStore::Base
include Coinmux::Facades
DEFAULT_BOOTSTRAP_HOST = "coinjoin.coinmux.com"
DEFAULT_P2P_PORT = 14141
PEER_DISCOVERY_TIMEOUT_SECONDS = 30
import 'java.io.IOException'
import 'java.net.InetAddress'
import 'java.net.Inet4Address'
import 'java.security.KeyPair'
import 'java.util.Random'
import 'net.tomp2p.futures.FutureBootstrap'
import 'net.tomp2p.futures.FutureDiscover'
import 'net.tomp2p.futures.FutureDHT'
import 'net.tomp2p.p2p.Peer'
import 'net.tomp2p.p2p.PeerMaker'
import 'net.tomp2p.peers.Number160'
import 'net.tomp2p.peers.PeerAddress'
import 'net.tomp2p.storage.Data'
def coin_join_identifier
@coin_join_identifier ||= (coin_join_uri.params["identifier"] || "coinjoins#{Coinmux.env == 'production' ? "" : "-#{Coinmux.env}"}")
end
def bootstrap_host
@bootstrap_host ||= (coin_join_uri.params["bootstrap"] || DEFAULT_BOOTSTRAP_HOST).gsub(/:.*/, "")
end
def bootstrap_port
@bootstrap_port ||= (
port = (coin_join_uri.params["bootstrap"] || "").gsub(/.*:/, "").to_i
port = DEFAULT_P2P_PORT if port == 0
port
)
end
def local_port
@local_port ||= (coin_join_uri.params["port"] || DEFAULT_P2P_PORT).to_i
end
def connect(&callback)
begin
address = Inet4Address.getByName(bootstrap_host)
@peer = PeerMaker.new(Number160.new(Random.new)).setPorts(local_port).makeAndListen()
peer_address = PeerAddress.new(Number160::ZERO, address, bootstrap_port, bootstrap_port)
@peer.getConfiguration().setBehindFirewall(true)
exec(@peer.discover().setDiscoverTimeoutSec(PEER_DISCOVERY_TIMEOUT_SECONDS).setPeerAddress(peer_address), callback) do |future|
if future.isSuccess()
@peer.bootstrap().start()
info "My external address is #{future.getPeerAddress()}"
self.connected = true
Coinmux::Event.new(data: future.getPeerAddress())
else
info "Failed #{future.getFailedReason()}"
Coinmux::Event.new(error: future.getFailedReason())
end
end
rescue
if block_given?
yield(Coinmux::Event.new(error: $!.to_s))
else
raise Coinmux::Error.new($!.to_s)
end
end
end
def disconnect(&callback)
self.connected = false
@peer.shutdown
if block_given?
yield(Coinmux::Event.new(data: :success))
end
end
def generate_identifier
Number160.new(Random.new).toString()
end
def convert_to_request_only_identifier(identifier)
# TODO: not sure how access control works
identifier
end
def identifier_can_insert?(identifier)
# TODO: not sure how access control works
true
end
def identifier_can_request?(identifier)
# TODO: not sure how access control works
true
end
def insert(identifier, data, &callback)
add_list(identifier, data, &callback)
end
def fetch_first(identifier, &callback)
get_list(identifier) do |event|
event.data = event.data.first if event.data
yield(event)
end
end
def fetch_last(identifier, &callback)
get_list(identifier) do |event|
event.data = event.data.last if event.data
yield(event)
end
end
def fetch_all(identifier, &callback)
get_list(identifier, &callback)
end
# items should be in reverse inserted order, but data returned as an unordered set by Tomp2p
def fetch_most_recent(identifier, max_items, &callback)
get_list(identifier) do |event|
event.data = (event.data[-1*max_items..-1] || event.data).reverse! if event.data
yield(event)
end
end
private
def peer
@peer
end
class FutureHandler < Java::NetTomp2pFutures::BaseFutureAdapter
attr_accessor :callback
def initialize(callback)
super()
self.callback = callback
end
def operationComplete(future)
callback.call(future)
end
end
def exec(startable, callback, &block)
future = startable.start()
if callback.nil?
future.awaitUninterruptibly()
event = block.call(future)
raise Coinmux::Error, event.error if event.error
event.data
else
handler_proc = lambda do |future|
event = block.call(future)
callback.call(event)
end
future.addListener(FutureHandler.new(handler_proc))
nil
end
end
def key_ttl
2 * 60 * 60
end
def current_key(key)
"#{Time.now.to_i / key_ttl * key_ttl}:#{key}"
end
def previous_key(key)
"#{Time.now.to_i / key_ttl * key_ttl - key_ttl}:#{key}"
end
def add_list(key, value, &callback)
key = current_key(key)
json = {
timestamp: Time.now.to_i, # TODO: need to come up with something better than timestamps here
value: value
}.to_json
exec(peer.add(create_hash(key)).setData(Data.new(json)), callback) do |future|
# exec(peer.add(create_hash(key)).setData(Data.new(json).set_ttl_seconds(11)).setRefreshSeconds(5).setDirectReplication(), callback) do |future|
if future.isSuccess()
Coinmux::Event.new(data: nil)
else
Coinmux::Event.new(error: future.getFailedReason())
end
end
end
def put(key, value, &callback)
key = current_key(key)
json = {
timestamp: Time.now.to_i, # TODO: need to come up with something better than timestamps here
value: value
}.to_json
exec(peer.put(create_hash(key)).setData(Data.new(json)), callback) do |future|
if future.isSuccess()
Coinmux::Event.new(data: nil)
else
Coinmux::Event.new(error: future.getFailedReason())
end
end
end
def get(key, &callback)
key = current_key(key)
exec(peer.get(create_hash(key)), callback) do |future|
if future.isSuccess()
value = JSON.parse(future.getData().getObject().to_s)['value'] rescue nil
Coinmux::Event.new(data: value)
else
Coinmux::Event.new(error: future.getFailedReason())
end
end
end
# TODO: I don't know how to get items to expire in the set, so we'll use a new set every hour, to let the
# old set expire. But we'll also look at the previous set. This should be fun for computers with incorrect time setup.
def get_list(key, &callback)
do_get_list(current_key(key)) do |prev_event|
do_get_list(previous_key(key)) do |current_event|
result_event = Coinmux::Event.new
if prev_event.data || current_event.data
result_event.data = (prev_event.data || []) + (current_event.data || [])
else
result_event.error = prev_event.error || current_event.error
end
yield(result_event)
end
end
end
def do_get_list(key, &callback)
# peer.get(create_hash(key)).setAll()
Thread.new do
peer.get(create_hash(key))
exec(peer.get(create_hash(key)).setAll(), callback) do |future|
if future.isSuccess()
hashes = future.getDataMap().values().each_with_object([]) do |value, hashes|
json = value.getObject().to_s
if (hash = JSON.parse(json) rescue nil)
if (timestamp = Time.at(hash['timestamp'].to_i).to_i rescue nil)
if Time.now.to_i - timestamp < Coinmux::DataStore::Base::DATA_TIME_TO_LIVE
hashes << hash
end
end
end
end.sort do |left, right|
left_timestamp, right_timestamp = [left, right].collect do |hash|
Time.at(hash['timestamp'].to_i)
end
left_timestamp <=> right_timestamp
end
data = hashes.collect { |hash| hash['value'].to_s }
Coinmux::Event.new(data: data)
elsif future.getFailedReason().to_s.include?("Expected >0 result, but got 0")
Coinmux::Event.new(data: [])
else
Coinmux::Event.new(error: future.getFailedReason())
end
end
end
nil
end
def create_hash(name)
Number160.java_send(:createHash, [java.lang.String], name)
end
end
|
michaelgpearce/coinmux
|
spec/message/transaction_signature_spec.rb
|
require 'spec_helper'
describe Coinmux::Message::TransactionSignature do
let(:template_message) { build(:transaction_signature_message) }
let(:coin_join) { template_message.coin_join }
let(:transaction_input_index) { template_message.transaction_input_index }
let(:script_sig) { template_message.script_sig }
let(:message_verification) { template_message.message_verification }
before do
stub_bitcoin_network_for_coin_join(coin_join)
end
describe "validations" do
let(:message) do
build(:transaction_signature_message,
transaction_input_index: transaction_input_index,
script_sig: script_sig,
message_verification: message_verification,
coin_join: coin_join)
end
subject { message.valid? }
it "is valid with default data" do
expect(subject).to be_true
end
describe "#message_verification_correct" do
let(:message_verification) { 'invalid-message-verification' }
it "is invalid with incorrect message_verification" do
expect(subject).to be_false
expect(message.errors[:message_verification]).to include("cannot be verified")
end
end
describe "#transaction_input_index_valid" do
it "is invalid with spent transaction" do
bitcoin_network_facade.should_receive(:transaction_input_unspent?).with(coin_join.transaction_object, transaction_input_index).and_return(false)
expect(subject).to be_false
expect(message.errors[:transaction_input_index]).to include("has been spent")
end
end
describe "#script_sig_valid" do
it "is invalid with script_sig" do
bitcoin_network_facade.should_receive(:script_sig_valid?).with(coin_join.transaction_object, transaction_input_index, Base64.decode64(script_sig)).and_return(false)
expect(subject).to be_false
expect(message.errors[:script_sig]).to include("is not valid")
end
end
end
describe "#build" do
let(:private_key_hex) { Helper.next_bitcoin_info[:private_key] }
let(:script_sig) { "scriptsig-#{rand}" }
subject { Coinmux::Message::TransactionSignature.build(coin_join, transaction_input_index: transaction_input_index, private_key: private_key_hex) }
before do
Coinmux::BitcoinNetwork.instance.stub(:build_transaction_input_script_sig).and_return(script_sig)
end
it "builds valid transaction_signature" do
expect(subject.valid?).to be_true
end
it "builds a script sig" do
Coinmux::BitcoinNetwork.instance.should_receive(:build_transaction_input_script_sig).with(coin_join.transaction_object, transaction_input_index, private_key_hex)
subject
end
it "base 64 encodes the script sig" do
script_sig = bitcoin_network_facade.build_transaction_input_script_sig(coin_join.transaction_object, transaction_input_index, private_key_hex)
expect(subject.script_sig).to eq(Base64.encode64(script_sig))
end
it "builds a message_verification" do
expect(subject.message_verification).to eq(coin_join.build_message_verification(:transaction_signature, transaction_input_index, script_sig))
end
end
describe "#from_json" do
let(:message) { template_message }
let(:json) do
{
transaction_input_index: message.transaction_input_index,
script_sig: message.script_sig,
message_verification: message.message_verification
}.to_json
end
subject do
Coinmux::Message::TransactionSignature.from_json(json, data_store, coin_join)
end
it "creates a valid transaction_signature" do
expect(subject).to_not be_nil
expect(subject.valid?).to be_true
expect(subject.transaction_input_index).to eq(message.transaction_input_index)
expect(subject.script_sig).to eq(message.script_sig)
expect(subject.message_verification).to eq(message.message_verification)
end
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/threading.rb
|
module Coinmux::Threading
def self.wait_for_callback(object, method, *args, &callback)
done = false
results = nil
object.send(method, *args) do |*callback_results|
done = true
results = callback_results
end
loop { break if done; sleep(0.05) }
results
end
def wait_for_callback(method, *args, &callback)
Coinmux::Threading.wait_for_callback(self, method, *args, &callback)
end
end
|
michaelgpearce/coinmux
|
cli/bootstrap.rb
|
<gh_stars>10-100
require 'fileutils'
class Cli::Bootstrap
DEFAULT_PORT = 14141
attr_accessor :port
import 'java.io.IOException'
import 'java.util.Random'
import 'net.tomp2p.p2p.Peer'
import 'net.tomp2p.p2p.PeerMaker'
import 'net.tomp2p.peers.Number160'
import 'net.tomp2p.storage.StorageDisk'
import 'net.tomp2p.storage.StorageGeneric'
def initialize(options = {})
options.assert_keys!(optional: :port)
self.port = options[:port].try(:to_i) || DEFAULT_PORT
end
def startup
puts "Starting bootstrap on port #{port}"
@peer = PeerMaker.new(Number160.new(Random.new)).setPorts(port).makeAndListen()
@peer.getPeerBean().setStorage(StorageDisk.new(storage_path));
@peer.getConfiguration().setBehindFirewall(true)
begin
loop do
sleep(0.05)
end
ensure
shutdown
end
end
private
def storage_path
Coinmux::FileUtil.root_mkdir_p('tmp', 'bootstrap_storage')
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/bitcoin_network.rb
|
class Coinmux::BitcoinNetwork
include Singleton, Coinmux::BitcoinUtil, Coinmux::Facades
import 'com.google.bitcoin.core.Transaction'
import 'java.math.BigInteger'
import 'java.security.SignatureException'
import 'com.google.bitcoin.core.Address'
import 'com.google.bitcoin.core.ECKey'
import 'com.google.bitcoin.core.NetworkParameters'
import 'com.google.bitcoin.core.PeerGroup'
import 'com.google.bitcoin.core.ScriptException'
import 'com.google.bitcoin.core.Utils'
import 'com.google.bitcoin.core.VerificationException'
import 'com.google.bitcoin.crypto.TransactionSignature'
import 'com.google.bitcoin.script.Script'
import 'com.google.bitcoin.script.ScriptBuilder'
import 'com.google.bitcoin.net.discovery.DnsDiscovery'
import 'org.spongycastle.util.encoders.Hex'
# @address [String] Input address.
# @callback [Proc, nil] Invoked with a Coinmux::Event with data or error set.
# @return [Hash] Hash with keys being `{id: 'transaction hash identifier', index: 'unspent transaction output index'}` and the value being the unspent amount. Only returns when no callback.
# @raise [Coinmux::Error] Only raises when no callback
def unspent_inputs_for_address(address, &callback)
exec(callback) do
data = webbtc_get_json("/address/#{address}.json")
build_unspent_inputs_from_data(data, address)
end
end
# @unspent_inputs [Array] Array of hashes with keys being `:id` (transaction hash identifier), `:index` (the index of the unspent output).
# @outputs [Array] Array of hashes with keys being `:address` and `:amount`.
# @callback [Proc, nil] Invoked with a Coinmux::Event with data or error set.
# @return [Object] A transaction with inputs linked to the transactions from `unspent_transaction_input_hashes` in the order specified. Only returns when no callback.
# @raise [Coinmux::Error] Only raises when no callback
def build_unsigned_transaction(unspent_inputs, outputs, &callback)
exec(callback) do
Transaction.new(network_params).tap do |transaction|
unspent_inputs.each do |tx_hash|
input_tx = fetch_transaction(tx_hash[:id])
raise Coinmux::Error, "Output index does not exist" if tx_hash[:index].to_s.to_i < 0 || tx_hash[:index].to_s.to_i >= input_tx.getOutputs().size()
tx_output = input_tx.getOutput(tx_hash[:index])
transaction.addInput(tx_output)
end
outputs.each do |hash|
transaction.addOutput(BigInteger.new(hash[:amount].to_s), Address.new(network_params, hash[:address]))
end
end
end
end
# @transaction [Object] Transaction returned from `#build_unsigned_transaction`.
# @input_index [Fixnum] The index of the input.
# @private_key_hex [String] The private key used to sign the input at this index.
# @return [String] The script_sig used for signing this (and only this) transaction.
# @raise [Coinmux::Error]
def build_transaction_input_script_sig(transaction, input_index, private_key_hex)
tx_input = get_unspent_tx_input(transaction, input_index)
key = build_ec_key(private_key_hex)
connected_pub_key_script = tx_input.getOutpoint().getConnectedPubKeyScript()
script_public_key = tx_input.getOutpoint().getConnectedOutput().getScriptPubKey().to_s
signature = transaction.calculateSignature(input_index, key, nil, connected_pub_key_script, Transaction::SigHash::ALL, false)
script_sig = ScriptBuilder.createInputScript(signature, key)
script_sig.getProgram().collect(&:to_i).pack('c*')
end
# @transaction [Object] Transaction returned from `#build_unsigned_transaction`
# @input_index [Fixnum] The index of the input.
# @return [true, false]
def transaction_input_unspent?(transaction, input_index)
begin
get_unspent_tx_input(transaction, input_index)
true
rescue Coinmux::Error
false
end
end
# @transaction [Object] Transaction returned from `#build_unsigned_transaction`
# @input_index [Fixnum] The index of the input.
# @script_sig [String] The script_sig used for signing this index.
# @return [true, false]
def script_sig_valid?(transaction, input_index, script_sig)
begin
set_transaction_script_sig(clone_transaction(transaction), input_index, script_sig)
true
rescue Coinmux::Error
debug "Script Sig is not valid: #{$!}"
false
end
end
# @transaction [Object] Transaction returned from `#build_unsigned_transaction`
# @input_index [Fixnum] The index of the input.
# @script_sig [String] The script_sig used for signing this index.
# @raise [Coinmux::Error]
def sign_transaction_input(transaction, input_index, script_sig)
set_transaction_script_sig(transaction, input_index, script_sig)
nil
end
# @transaction [Object] Transaction returned from `#build_unsigned_transaction` and all inputs signed with `#sign_transaction_input`
# @callback [Proc, nil] Invoked with a Coinmux::Event with data or error set.
# @return [String] The transaction hash. Only returns when no callback.
# @raise [Coinmux::Error] Only raises when no callback
def post_transaction(transaction, &callback)
exec(callback) do
result = webbtc_post_bin("/relay_tx", tx: transaction.bitcoinSerialize().collect(&:to_i).pack('c*').unpack('H*').first)
result['hash']
end
end
private
def clone_transaction(source)
inputs = source.getInputs().collect do |input|
out = input.getOutpoint()
{ id: out.getHash().toString(), index: out.getIndex() }
end
outputs = source.getOutputs().collect do |output|
{ address: output.getScriptPubKey().getToAddress(network_params).toString(), amount: output.getValue() }
end
build_unsigned_transaction(inputs, outputs)
end
def set_transaction_script_sig(transaction, input_index, script_sig)
begin
script_sig = Script.new(script_sig.unpack('c*').to_java(:byte))
tx_input = get_unspent_tx_input(transaction, input_index)
tx_input.setScriptSig(script_sig)
tx_input.verify()
tx_input
rescue ScriptException => e
raise Coinmux::Error, "Unable to verify signature: #{e}"
rescue VerificationException => e
raise Coinmux::Error, "Unable to verify signature: #{e}"
end
end
def fetch_transaction(transaction_hash)
bytes = webbtc_get_bin("/tx/#{transaction_hash}.bin").unpack('c*').to_java(:byte)
Transaction.new(network_params, bytes)
end
# @transaction [Object] Transaction returned from `#build_unsigned_transaction`
# @input_index [Fixnum] The index of the input.
# @return [TransactionInput] A verified unspent input.
# @raise [Coinmux::Error]
def get_unspent_tx_input(transaction, input_index)
input_index = input_index.to_s.to_i
raise Coinmux::Error, "Invalid input index" if input_index < 0 || input_index >= transaction.getInputs().size()
tx_input = transaction.getInput(input_index)
raise Coinmux::Error, "No connected output: #{tx_input}" if tx_input.getOutpoint().getConnectedOutput().nil?
raise Coinmux::Error, "Signing already signed transaction: #{tx_input}" if tx_input.getScriptBytes().length != 0
begin
tx_input.getScriptSig().correctlySpends(transaction, input_index, tx_input.getOutpoint().getConnectedOutput().getScriptPubKey(), true)
raise Coinmux::Error, "Input already spent: #{tx_input}"
rescue ScriptException
# input not spent... what we want
end
tx_input
end
def build_unspent_inputs_from_data(data, address)
all_inputs = data['transactions'].values.inject({}) do |acc, txn|
txn['out'].each_with_index do |out, index|
if out['address'] == address
acc[{id: txn['hash'], index: index}] = (out['value'].to_f * SATOSHIS_PER_BITCOIN).to_i
end
end
acc
end
unspent_inputs = data['transactions'].values.inject(all_inputs.dup) do |acc, txn|
txn['in'].each do |in_|
next unless prev_out = in_['prev_out']
acc.delete({id: prev_out['hash'], index: prev_out['n']})
end
acc
end
unspent_inputs
end
def build_ec_key(private_key_hex)
ECKey.new(BigInteger.new(private_key_hex, 16))
end
def exec(callback, &block)
exec = lambda do
begin
result = yield
Coinmux::Event.new(data: result)
rescue Coinmux::Error => e
Coinmux::Event.new(error: e.message)
rescue StandardError => e
puts e, e.backtrace
Coinmux::Event.new(error: "Unknown error: #{e.message}")
end
end
if callback.nil?
event = exec.call
raise Coinmux::Error, event.error if event.error
event.data
else
Thread.new do
callback.call(exec.call)
end
nil
end
end
def webbtc_post_bin(path, data)
result = http_facade.post(config_facade.webbtc_host, path, data)
hash = JSON.parse(result) rescue nil
if hash.nil?
raise Coinmux::Error, "Unable to post to #{path}: invalid JSON response"
elsif hash['error']
raise Coinmux::Error, "Unable to post to #{path}: #{hash['error']} (#{hash['detail']})"
end
hash
end
def webbtc_get_bin(path)
http_facade.get(config_facade.webbtc_host, path)
end
def webbtc_get_json(path)
result = http_facade.get(config_facade.webbtc_host, path)
hash = JSON.parse(result) rescue nil
if hash.nil?
raise Coinmux::Error, "Unable to parse JSON"
elsif hash['error']
raise Coinmux::Error, "Invalid request: #{hash['error']}"
end
hash
end
end
|
michaelgpearce/coinmux
|
spec/message/output_spec.rb
|
require 'spec_helper'
describe Coinmux::Message::Output do
before do
fake_all_network_connections
end
let(:coin_join) { build(:coin_join_message, :with_inputs, :with_message_verification, :with_outputs) }
let(:message) { coin_join.outputs.value.detect(&:created_with_build?) }
describe "validations" do
subject { message.valid? }
it "is valid with default data" do
subject
expect(subject).to be_true
end
describe "#message_verification_correct" do
before do
expect(coin_join.director?).to be_true
end
context "with invalid value" do
before do
message.message_verification = coin_join.build_message_verification(:output, 'not correct')
end
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:message_verification]).to include("cannot be verified")
end
end
end
describe "#address_valid" do
context "with invalid address" do
before do
message.address = "invalid_address"
end
it "is invalid" do
expect(subject).to be_false
expect(message.errors[:address]).to include("is not a valid address")
end
end
end
end
describe "#build" do
let(:address) { message.address }
subject { Coinmux::Message::Output.build(coin_join, address: address) }
it "builds valid output" do
expect(subject.valid?).to be_true
end
it "has address" do
expect(subject.address).to eq(address)
end
it "has random identifier for transaction_output_identifier" do
expect(subject.transaction_output_identifier).to_not be_nil
end
it "has message verification" do
expect(subject.message_verification).to eq(coin_join.build_message_verification(:output, address))
end
end
describe "#from_json" do
let(:json) do
{
address: message.address,
transaction_output_identifier: message.transaction_output_identifier,
message_verification: message.message_verification,
}.to_json
end
subject do
Coinmux::Message::Output.from_json(json, data_store, coin_join)
end
it "creates a valid output" do
expect(subject).to_not be_nil
expect(subject.valid?).to be_true
expect(subject.address).to eq(message.address)
expect(subject.transaction_output_identifier).to eq(message.transaction_output_identifier)
expect(subject.message_verification).to eq(message.message_verification)
end
end
end
|
michaelgpearce/coinmux
|
lib/coinmux/event.rb
|
class Coinmux::Event
attr_accessor :error, :data
def initialize(params = {})
params.each do |key, value|
send("#{key}=", value)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.