id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
18,100
documentcloud/cloud-crowd
lib/cloud_crowd/models/node_record.rb
CloudCrowd.NodeRecord.send_work_unit
def send_work_unit(unit) result = node['/work'].post(:work_unit => unit.to_json) unit.assign_to(self, JSON.parse(result.body)['pid']) touch && true rescue RestClient::RequestTimeout # The node's gone away. Destroy it and it will check in when it comes back CloudCrowd.log "Node #{host} received RequestTimeout, removing it" destroy && false rescue RestClient::RequestFailed => e raise e unless e.http_code == 503 && e.http_body == Node::OVERLOADED_MESSAGE update_attribute(:busy, true) && false rescue RestClient::Exception, Errno::ECONNREFUSED, Timeout::Error, Errno::ECONNRESET=>e # Couldn't post to node, assume it's gone away. CloudCrowd.log "Node #{host} received #{e.class} #{e}, removing it" destroy && false end
ruby
def send_work_unit(unit) result = node['/work'].post(:work_unit => unit.to_json) unit.assign_to(self, JSON.parse(result.body)['pid']) touch && true rescue RestClient::RequestTimeout # The node's gone away. Destroy it and it will check in when it comes back CloudCrowd.log "Node #{host} received RequestTimeout, removing it" destroy && false rescue RestClient::RequestFailed => e raise e unless e.http_code == 503 && e.http_body == Node::OVERLOADED_MESSAGE update_attribute(:busy, true) && false rescue RestClient::Exception, Errno::ECONNREFUSED, Timeout::Error, Errno::ECONNRESET=>e # Couldn't post to node, assume it's gone away. CloudCrowd.log "Node #{host} received #{e.class} #{e}, removing it" destroy && false end
[ "def", "send_work_unit", "(", "unit", ")", "result", "=", "node", "[", "'/work'", "]", ".", "post", "(", ":work_unit", "=>", "unit", ".", "to_json", ")", "unit", ".", "assign_to", "(", "self", ",", "JSON", ".", "parse", "(", "result", ".", "body", ")", "[", "'pid'", "]", ")", "touch", "&&", "true", "rescue", "RestClient", "::", "RequestTimeout", "# The node's gone away. Destroy it and it will check in when it comes back", "CloudCrowd", ".", "log", "\"Node #{host} received RequestTimeout, removing it\"", "destroy", "&&", "false", "rescue", "RestClient", "::", "RequestFailed", "=>", "e", "raise", "e", "unless", "e", ".", "http_code", "==", "503", "&&", "e", ".", "http_body", "==", "Node", "::", "OVERLOADED_MESSAGE", "update_attribute", "(", ":busy", ",", "true", ")", "&&", "false", "rescue", "RestClient", "::", "Exception", ",", "Errno", "::", "ECONNREFUSED", ",", "Timeout", "::", "Error", ",", "Errno", "::", "ECONNRESET", "=>", "e", "# Couldn't post to node, assume it's gone away.", "CloudCrowd", ".", "log", "\"Node #{host} received #{e.class} #{e}, removing it\"", "destroy", "&&", "false", "end" ]
Dispatch a WorkUnit to this node. Places the node at back at the end of the rotation. If we fail to send the WorkUnit, we consider the node to be down, and remove this record, freeing up all of its checked-out work units. If the Node responds that it's overloaded, we mark it as busy. Returns true if the WorkUnit was dispatched successfully.
[ "Dispatch", "a", "WorkUnit", "to", "this", "node", ".", "Places", "the", "node", "at", "back", "at", "the", "end", "of", "the", "rotation", ".", "If", "we", "fail", "to", "send", "the", "WorkUnit", "we", "consider", "the", "node", "to", "be", "down", "and", "remove", "this", "record", "freeing", "up", "all", "of", "its", "checked", "-", "out", "work", "units", ".", "If", "the", "Node", "responds", "that", "it", "s", "overloaded", "we", "mark", "it", "as", "busy", ".", "Returns", "true", "if", "the", "WorkUnit", "was", "dispatched", "successfully", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/node_record.rb#L53-L68
18,101
documentcloud/cloud-crowd
lib/cloud_crowd/models/work_unit.rb
CloudCrowd.WorkUnit.fail
def fail(output, time_taken) tries = self.attempts + 1 return try_again if tries < CloudCrowd.config[:work_unit_retries] update_attributes({ :status => FAILED, :node_record => nil, :worker_pid => nil, :attempts => tries, :output => output, :time => time_taken }) job && job.check_for_completion end
ruby
def fail(output, time_taken) tries = self.attempts + 1 return try_again if tries < CloudCrowd.config[:work_unit_retries] update_attributes({ :status => FAILED, :node_record => nil, :worker_pid => nil, :attempts => tries, :output => output, :time => time_taken }) job && job.check_for_completion end
[ "def", "fail", "(", "output", ",", "time_taken", ")", "tries", "=", "self", ".", "attempts", "+", "1", "return", "try_again", "if", "tries", "<", "CloudCrowd", ".", "config", "[", ":work_unit_retries", "]", "update_attributes", "(", "{", ":status", "=>", "FAILED", ",", ":node_record", "=>", "nil", ",", ":worker_pid", "=>", "nil", ",", ":attempts", "=>", "tries", ",", ":output", "=>", "output", ",", ":time", "=>", "time_taken", "}", ")", "job", "&&", "job", ".", "check_for_completion", "end" ]
Mark this unit as having failed. May attempt a retry.
[ "Mark", "this", "unit", "as", "having", "failed", ".", "May", "attempt", "a", "retry", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/work_unit.rb#L138-L150
18,102
documentcloud/cloud-crowd
lib/cloud_crowd/worker.rb
CloudCrowd.Worker.complete_work_unit
def complete_work_unit(result) keep_trying_to "complete work unit" do data = base_params.merge({:status => 'succeeded', :output => result}) @node.central["/work/#{data[:id]}"].put(data) log "finished #{display_work_unit} in #{data[:time]} seconds" end end
ruby
def complete_work_unit(result) keep_trying_to "complete work unit" do data = base_params.merge({:status => 'succeeded', :output => result}) @node.central["/work/#{data[:id]}"].put(data) log "finished #{display_work_unit} in #{data[:time]} seconds" end end
[ "def", "complete_work_unit", "(", "result", ")", "keep_trying_to", "\"complete work unit\"", "do", "data", "=", "base_params", ".", "merge", "(", "{", ":status", "=>", "'succeeded'", ",", ":output", "=>", "result", "}", ")", "@node", ".", "central", "[", "\"/work/#{data[:id]}\"", "]", ".", "put", "(", "data", ")", "log", "\"finished #{display_work_unit} in #{data[:time]} seconds\"", "end", "end" ]
A new Worker customizes itself to its WorkUnit at instantiation. Return output to the central server, marking the WorkUnit done.
[ "A", "new", "Worker", "customizes", "itself", "to", "its", "WorkUnit", "at", "instantiation", ".", "Return", "output", "to", "the", "central", "server", "marking", "the", "WorkUnit", "done", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L33-L39
18,103
documentcloud/cloud-crowd
lib/cloud_crowd/worker.rb
CloudCrowd.Worker.fail_work_unit
def fail_work_unit(exception) keep_trying_to "mark work unit as failed" do data = base_params.merge({:status => 'failed', :output => {'output' => exception.message}.to_json}) @node.central["/work/#{data[:id]}"].put(data) log "failed #{display_work_unit} in #{data[:time]} seconds\n#{exception.message}\n#{exception.backtrace}" end end
ruby
def fail_work_unit(exception) keep_trying_to "mark work unit as failed" do data = base_params.merge({:status => 'failed', :output => {'output' => exception.message}.to_json}) @node.central["/work/#{data[:id]}"].put(data) log "failed #{display_work_unit} in #{data[:time]} seconds\n#{exception.message}\n#{exception.backtrace}" end end
[ "def", "fail_work_unit", "(", "exception", ")", "keep_trying_to", "\"mark work unit as failed\"", "do", "data", "=", "base_params", ".", "merge", "(", "{", ":status", "=>", "'failed'", ",", ":output", "=>", "{", "'output'", "=>", "exception", ".", "message", "}", ".", "to_json", "}", ")", "@node", ".", "central", "[", "\"/work/#{data[:id]}\"", "]", ".", "put", "(", "data", ")", "log", "\"failed #{display_work_unit} in #{data[:time]} seconds\\n#{exception.message}\\n#{exception.backtrace}\"", "end", "end" ]
Mark the WorkUnit failed, returning the exception to central.
[ "Mark", "the", "WorkUnit", "failed", "returning", "the", "exception", "to", "central", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L42-L48
18,104
documentcloud/cloud-crowd
lib/cloud_crowd/worker.rb
CloudCrowd.Worker.keep_trying_to
def keep_trying_to(title) begin yield rescue RestClient::ResourceNotFound => e log "work unit ##{@unit['id']} doesn't exist. discarding..." rescue Exception => e log "failed to #{title} -- retry in #{@retry_wait} seconds" log e.message log e.backtrace sleep @retry_wait retry end end
ruby
def keep_trying_to(title) begin yield rescue RestClient::ResourceNotFound => e log "work unit ##{@unit['id']} doesn't exist. discarding..." rescue Exception => e log "failed to #{title} -- retry in #{@retry_wait} seconds" log e.message log e.backtrace sleep @retry_wait retry end end
[ "def", "keep_trying_to", "(", "title", ")", "begin", "yield", "rescue", "RestClient", "::", "ResourceNotFound", "=>", "e", "log", "\"work unit ##{@unit['id']} doesn't exist. discarding...\"", "rescue", "Exception", "=>", "e", "log", "\"failed to #{title} -- retry in #{@retry_wait} seconds\"", "log", "e", ".", "message", "log", "e", ".", "backtrace", "sleep", "@retry_wait", "retry", "end", "end" ]
We expect and require internal communication between the central server and the workers to succeed. If it fails for any reason, log it, and then keep trying the same request.
[ "We", "expect", "and", "require", "internal", "communication", "between", "the", "central", "server", "and", "the", "workers", "to", "succeed", ".", "If", "it", "fails", "for", "any", "reason", "log", "it", "and", "then", "keep", "trying", "the", "same", "request", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L53-L65
18,105
documentcloud/cloud-crowd
lib/cloud_crowd/worker.rb
CloudCrowd.Worker.run_work_unit
def run_work_unit begin result = nil action_class = CloudCrowd.actions[@unit['action']] action = action_class.new(@status, @unit['input'], enhanced_unit_options, @node.asset_store) Dir.chdir(action.work_directory) do result = case @status when PROCESSING then action.process when SPLITTING then action.split when MERGING then action.merge else raise Error::StatusUnspecified, "work units must specify their status" end end action.cleanup_work_directory if action complete_work_unit({'output' => result}.to_json) rescue Exception => e action.cleanup_work_directory if action fail_work_unit(e) end @node.resolve_work(@unit['id']) end
ruby
def run_work_unit begin result = nil action_class = CloudCrowd.actions[@unit['action']] action = action_class.new(@status, @unit['input'], enhanced_unit_options, @node.asset_store) Dir.chdir(action.work_directory) do result = case @status when PROCESSING then action.process when SPLITTING then action.split when MERGING then action.merge else raise Error::StatusUnspecified, "work units must specify their status" end end action.cleanup_work_directory if action complete_work_unit({'output' => result}.to_json) rescue Exception => e action.cleanup_work_directory if action fail_work_unit(e) end @node.resolve_work(@unit['id']) end
[ "def", "run_work_unit", "begin", "result", "=", "nil", "action_class", "=", "CloudCrowd", ".", "actions", "[", "@unit", "[", "'action'", "]", "]", "action", "=", "action_class", ".", "new", "(", "@status", ",", "@unit", "[", "'input'", "]", ",", "enhanced_unit_options", ",", "@node", ".", "asset_store", ")", "Dir", ".", "chdir", "(", "action", ".", "work_directory", ")", "do", "result", "=", "case", "@status", "when", "PROCESSING", "then", "action", ".", "process", "when", "SPLITTING", "then", "action", ".", "split", "when", "MERGING", "then", "action", ".", "merge", "else", "raise", "Error", "::", "StatusUnspecified", ",", "\"work units must specify their status\"", "end", "end", "action", ".", "cleanup_work_directory", "if", "action", "complete_work_unit", "(", "{", "'output'", "=>", "result", "}", ".", "to_json", ")", "rescue", "Exception", "=>", "e", "action", ".", "cleanup_work_directory", "if", "action", "fail_work_unit", "(", "e", ")", "end", "@node", ".", "resolve_work", "(", "@unit", "[", "'id'", "]", ")", "end" ]
Executes the WorkUnit by running the Action, catching all exceptions as failures. We capture the thread so that we can kill it from the outside, when exiting.
[ "Executes", "the", "WorkUnit", "by", "running", "the", "Action", "catching", "all", "exceptions", "as", "failures", ".", "We", "capture", "the", "thread", "so", "that", "we", "can", "kill", "it", "from", "the", "outside", "when", "exiting", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L75-L95
18,106
documentcloud/cloud-crowd
lib/cloud_crowd/worker.rb
CloudCrowd.Worker.run
def run trap_signals log "starting #{display_work_unit}" if @unit['options']['benchmark'] log("ran #{display_work_unit} in " + Benchmark.measure { run_work_unit }.to_s) else run_work_unit end Process.exit! end
ruby
def run trap_signals log "starting #{display_work_unit}" if @unit['options']['benchmark'] log("ran #{display_work_unit} in " + Benchmark.measure { run_work_unit }.to_s) else run_work_unit end Process.exit! end
[ "def", "run", "trap_signals", "log", "\"starting #{display_work_unit}\"", "if", "@unit", "[", "'options'", "]", "[", "'benchmark'", "]", "log", "(", "\"ran #{display_work_unit} in \"", "+", "Benchmark", ".", "measure", "{", "run_work_unit", "}", ".", "to_s", ")", "else", "run_work_unit", "end", "Process", ".", "exit!", "end" ]
Run this worker inside of a fork. Attempts to exit cleanly. Wraps run_work_unit to benchmark the execution time, if requested.
[ "Run", "this", "worker", "inside", "of", "a", "fork", ".", "Attempts", "to", "exit", "cleanly", ".", "Wraps", "run_work_unit", "to", "benchmark", "the", "execution", "time", "if", "requested", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L99-L108
18,107
documentcloud/cloud-crowd
lib/cloud_crowd/worker.rb
CloudCrowd.Worker.trap_signals
def trap_signals Signal.trap('QUIT') { Process.exit! } Signal.trap('INT') { Process.exit! } Signal.trap('TERM') { Process.exit! } end
ruby
def trap_signals Signal.trap('QUIT') { Process.exit! } Signal.trap('INT') { Process.exit! } Signal.trap('TERM') { Process.exit! } end
[ "def", "trap_signals", "Signal", ".", "trap", "(", "'QUIT'", ")", "{", "Process", ".", "exit!", "}", "Signal", ".", "trap", "(", "'INT'", ")", "{", "Process", ".", "exit!", "}", "Signal", ".", "trap", "(", "'TERM'", ")", "{", "Process", ".", "exit!", "}", "end" ]
When signaled to exit, make sure that the Worker shuts down without firing the Node's at_exit callbacks.
[ "When", "signaled", "to", "exit", "make", "sure", "that", "the", "Worker", "shuts", "down", "without", "firing", "the", "Node", "s", "at_exit", "callbacks", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/worker.rb#L144-L148
18,108
documentcloud/cloud-crowd
lib/cloud_crowd/command_line.rb
CloudCrowd.CommandLine.start_server
def start_server port = @options[:port] || 9173 daemonize = @options[:daemonize] ? '-d' : '' log_path = CloudCrowd.log_path('server.log') pid_path = CloudCrowd.pid_path('server.pid') rackup_path = File.expand_path("#{@options[:config_path]}/config.ru") FileUtils.mkdir_p(CloudCrowd.log_path) if @options[:daemonize] && !File.exists?(CloudCrowd.log_path) puts "Starting CloudCrowd Central Server (#{VERSION}) on port #{port}..." exec "thin -e #{@options[:environment]} -p #{port} #{daemonize} --tag cloud-crowd-server --log #{log_path} --pid #{pid_path} -R #{rackup_path} start" end
ruby
def start_server port = @options[:port] || 9173 daemonize = @options[:daemonize] ? '-d' : '' log_path = CloudCrowd.log_path('server.log') pid_path = CloudCrowd.pid_path('server.pid') rackup_path = File.expand_path("#{@options[:config_path]}/config.ru") FileUtils.mkdir_p(CloudCrowd.log_path) if @options[:daemonize] && !File.exists?(CloudCrowd.log_path) puts "Starting CloudCrowd Central Server (#{VERSION}) on port #{port}..." exec "thin -e #{@options[:environment]} -p #{port} #{daemonize} --tag cloud-crowd-server --log #{log_path} --pid #{pid_path} -R #{rackup_path} start" end
[ "def", "start_server", "port", "=", "@options", "[", ":port", "]", "||", "9173", "daemonize", "=", "@options", "[", ":daemonize", "]", "?", "'-d'", ":", "''", "log_path", "=", "CloudCrowd", ".", "log_path", "(", "'server.log'", ")", "pid_path", "=", "CloudCrowd", ".", "pid_path", "(", "'server.pid'", ")", "rackup_path", "=", "File", ".", "expand_path", "(", "\"#{@options[:config_path]}/config.ru\"", ")", "FileUtils", ".", "mkdir_p", "(", "CloudCrowd", ".", "log_path", ")", "if", "@options", "[", ":daemonize", "]", "&&", "!", "File", ".", "exists?", "(", "CloudCrowd", ".", "log_path", ")", "puts", "\"Starting CloudCrowd Central Server (#{VERSION}) on port #{port}...\"", "exec", "\"thin -e #{@options[:environment]} -p #{port} #{daemonize} --tag cloud-crowd-server --log #{log_path} --pid #{pid_path} -R #{rackup_path} start\"", "end" ]
Convenience command for quickly spinning up the central server. More sophisticated deployments, load-balancing across multiple app servers, should use the config.ru rackup file directly. This method will start a single Thin server.
[ "Convenience", "command", "for", "quickly", "spinning", "up", "the", "central", "server", ".", "More", "sophisticated", "deployments", "load", "-", "balancing", "across", "multiple", "app", "servers", "should", "use", "the", "config", ".", "ru", "rackup", "file", "directly", ".", "This", "method", "will", "start", "a", "single", "Thin", "server", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L80-L89
18,109
documentcloud/cloud-crowd
lib/cloud_crowd/command_line.rb
CloudCrowd.CommandLine.run_install
def run_install(install_path) require 'fileutils' install_path ||= '.' FileUtils.mkdir_p install_path unless File.exists?(install_path) install_file "#{CC_ROOT}/config/config.example.yml", "#{install_path}/config.yml" install_file "#{CC_ROOT}/config/config.example.ru", "#{install_path}/config.ru" install_file "#{CC_ROOT}/config/database.example.yml", "#{install_path}/database.yml" install_file "#{CC_ROOT}/actions", "#{install_path}/actions", true end
ruby
def run_install(install_path) require 'fileutils' install_path ||= '.' FileUtils.mkdir_p install_path unless File.exists?(install_path) install_file "#{CC_ROOT}/config/config.example.yml", "#{install_path}/config.yml" install_file "#{CC_ROOT}/config/config.example.ru", "#{install_path}/config.ru" install_file "#{CC_ROOT}/config/database.example.yml", "#{install_path}/database.yml" install_file "#{CC_ROOT}/actions", "#{install_path}/actions", true end
[ "def", "run_install", "(", "install_path", ")", "require", "'fileutils'", "install_path", "||=", "'.'", "FileUtils", ".", "mkdir_p", "install_path", "unless", "File", ".", "exists?", "(", "install_path", ")", "install_file", "\"#{CC_ROOT}/config/config.example.yml\"", ",", "\"#{install_path}/config.yml\"", "install_file", "\"#{CC_ROOT}/config/config.example.ru\"", ",", "\"#{install_path}/config.ru\"", "install_file", "\"#{CC_ROOT}/config/database.example.yml\"", ",", "\"#{install_path}/database.yml\"", "install_file", "\"#{CC_ROOT}/actions\"", ",", "\"#{install_path}/actions\"", ",", "true", "end" ]
Install the required CloudCrowd configuration files into the specified directory, or the current one.
[ "Install", "the", "required", "CloudCrowd", "configuration", "files", "into", "the", "specified", "directory", "or", "the", "current", "one", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L143-L151
18,110
documentcloud/cloud-crowd
lib/cloud_crowd/command_line.rb
CloudCrowd.CommandLine.ensure_config
def ensure_config return if @config_found found = CONFIG_FILES.all? {|f| File.exists? "#{@options[:config_path]}/#{f}" } found ? @config_dir = true : config_not_found end
ruby
def ensure_config return if @config_found found = CONFIG_FILES.all? {|f| File.exists? "#{@options[:config_path]}/#{f}" } found ? @config_dir = true : config_not_found end
[ "def", "ensure_config", "return", "if", "@config_found", "found", "=", "CONFIG_FILES", ".", "all?", "{", "|", "f", "|", "File", ".", "exists?", "\"#{@options[:config_path]}/#{f}\"", "}", "found", "?", "@config_dir", "=", "true", ":", "config_not_found", "end" ]
Check for configuration files, either in the current directory, or in the CLOUD_CROWD_CONFIG environment variable. Exit if they're not found.
[ "Check", "for", "configuration", "files", "either", "in", "the", "current", "directory", "or", "in", "the", "CLOUD_CROWD_CONFIG", "environment", "variable", ".", "Exit", "if", "they", "re", "not", "found", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L170-L174
18,111
documentcloud/cloud-crowd
lib/cloud_crowd/command_line.rb
CloudCrowd.CommandLine.install_file
def install_file(source, dest, is_dir=false) if File.exists?(dest) print "#{dest} already exists. Overwrite it? (yes/no) " return unless ['y', 'yes', 'ok'].include? gets.chomp.downcase end is_dir ? FileUtils.cp_r(source, dest) : FileUtils.cp(source, dest) puts "installed #{dest}" unless ENV['RACK_ENV'] == 'test' end
ruby
def install_file(source, dest, is_dir=false) if File.exists?(dest) print "#{dest} already exists. Overwrite it? (yes/no) " return unless ['y', 'yes', 'ok'].include? gets.chomp.downcase end is_dir ? FileUtils.cp_r(source, dest) : FileUtils.cp(source, dest) puts "installed #{dest}" unless ENV['RACK_ENV'] == 'test' end
[ "def", "install_file", "(", "source", ",", "dest", ",", "is_dir", "=", "false", ")", "if", "File", ".", "exists?", "(", "dest", ")", "print", "\"#{dest} already exists. Overwrite it? (yes/no) \"", "return", "unless", "[", "'y'", ",", "'yes'", ",", "'ok'", "]", ".", "include?", "gets", ".", "chomp", ".", "downcase", "end", "is_dir", "?", "FileUtils", ".", "cp_r", "(", "source", ",", "dest", ")", ":", "FileUtils", ".", "cp", "(", "source", ",", "dest", ")", "puts", "\"installed #{dest}\"", "unless", "ENV", "[", "'RACK_ENV'", "]", "==", "'test'", "end" ]
Install a file and log the installation. If we're overwriting a file, offer a chance to back out.
[ "Install", "a", "file", "and", "log", "the", "installation", ".", "If", "we", "re", "overwriting", "a", "file", "offer", "a", "chance", "to", "back", "out", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/command_line.rb#L236-L243
18,112
documentcloud/cloud-crowd
lib/cloud_crowd/models/job.rb
CloudCrowd.Job.check_for_completion
def check_for_completion return unless all_work_units_complete? set_next_status outs = gather_outputs_from_work_units return queue_for_workers([outs]) if merging? if complete? update_attributes(:outputs => outs, :time => time_taken) CloudCrowd.log "Job ##{id} (#{action}) #{display_status}." unless ENV['RACK_ENV'] == 'test' CloudCrowd.defer { fire_callback } if callback_url end self end
ruby
def check_for_completion return unless all_work_units_complete? set_next_status outs = gather_outputs_from_work_units return queue_for_workers([outs]) if merging? if complete? update_attributes(:outputs => outs, :time => time_taken) CloudCrowd.log "Job ##{id} (#{action}) #{display_status}." unless ENV['RACK_ENV'] == 'test' CloudCrowd.defer { fire_callback } if callback_url end self end
[ "def", "check_for_completion", "return", "unless", "all_work_units_complete?", "set_next_status", "outs", "=", "gather_outputs_from_work_units", "return", "queue_for_workers", "(", "[", "outs", "]", ")", "if", "merging?", "if", "complete?", "update_attributes", "(", ":outputs", "=>", "outs", ",", ":time", "=>", "time_taken", ")", "CloudCrowd", ".", "log", "\"Job ##{id} (#{action}) #{display_status}.\"", "unless", "ENV", "[", "'RACK_ENV'", "]", "==", "'test'", "CloudCrowd", ".", "defer", "{", "fire_callback", "}", "if", "callback_url", "end", "self", "end" ]
After work units are marked successful, we check to see if all of them have finished, if so, continue on to the next phase of the job.
[ "After", "work", "units", "are", "marked", "successful", "we", "check", "to", "see", "if", "all", "of", "them", "have", "finished", "if", "so", "continue", "on", "to", "the", "next", "phase", "of", "the", "job", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L51-L62
18,113
documentcloud/cloud-crowd
lib/cloud_crowd/models/job.rb
CloudCrowd.Job.percent_complete
def percent_complete return 99 if merging? return 100 if complete? unit_count = work_units.count return 100 if unit_count <= 0 (work_units.complete.count / unit_count.to_f * 100).round end
ruby
def percent_complete return 99 if merging? return 100 if complete? unit_count = work_units.count return 100 if unit_count <= 0 (work_units.complete.count / unit_count.to_f * 100).round end
[ "def", "percent_complete", "return", "99", "if", "merging?", "return", "100", "if", "complete?", "unit_count", "=", "work_units", ".", "count", "return", "100", "if", "unit_count", "<=", "0", "(", "work_units", ".", "complete", ".", "count", "/", "unit_count", ".", "to_f", "*", "100", ")", ".", "round", "end" ]
How complete is this Job? Unfortunately, with the current processing sequence, the percent_complete can pull a fast one and go backwards. This happens when there's a single large input that takes a long time to split, and when it finally does it creates a whole swarm of work units. This seems unavoidable.
[ "How", "complete", "is", "this", "Job?", "Unfortunately", "with", "the", "current", "processing", "sequence", "the", "percent_complete", "can", "pull", "a", "fast", "one", "and", "go", "backwards", ".", "This", "happens", "when", "there", "s", "a", "single", "large", "input", "that", "takes", "a", "long", "time", "to", "split", "and", "when", "it", "finally", "does", "it", "creates", "a", "whole", "swarm", "of", "work", "units", ".", "This", "seems", "unavoidable", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L143-L149
18,114
documentcloud/cloud-crowd
lib/cloud_crowd/models/job.rb
CloudCrowd.Job.as_json
def as_json(opts={}) atts = { 'id' => id, 'color' => color, 'status' => display_status, 'percent_complete' => percent_complete, 'work_units' => work_units.count, 'time_taken' => time_taken } atts['outputs'] = JSON.parse(outputs) if outputs atts['email'] = email if email atts end
ruby
def as_json(opts={}) atts = { 'id' => id, 'color' => color, 'status' => display_status, 'percent_complete' => percent_complete, 'work_units' => work_units.count, 'time_taken' => time_taken } atts['outputs'] = JSON.parse(outputs) if outputs atts['email'] = email if email atts end
[ "def", "as_json", "(", "opts", "=", "{", "}", ")", "atts", "=", "{", "'id'", "=>", "id", ",", "'color'", "=>", "color", ",", "'status'", "=>", "display_status", ",", "'percent_complete'", "=>", "percent_complete", ",", "'work_units'", "=>", "work_units", ".", "count", ",", "'time_taken'", "=>", "time_taken", "}", "atts", "[", "'outputs'", "]", "=", "JSON", ".", "parse", "(", "outputs", ")", "if", "outputs", "atts", "[", "'email'", "]", "=", "email", "if", "email", "atts", "end" ]
A JSON representation of this job includes the statuses of its component WorkUnits, as well as any completed outputs.
[ "A", "JSON", "representation", "of", "this", "job", "includes", "the", "statuses", "of", "its", "component", "WorkUnits", "as", "well", "as", "any", "completed", "outputs", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L164-L176
18,115
documentcloud/cloud-crowd
lib/cloud_crowd/models/job.rb
CloudCrowd.Job.gather_outputs_from_work_units
def gather_outputs_from_work_units units = self.work_units.complete outs = self.work_units.complete.map {|u| u.parsed_output } self.work_units.complete.destroy_all outs.to_json end
ruby
def gather_outputs_from_work_units units = self.work_units.complete outs = self.work_units.complete.map {|u| u.parsed_output } self.work_units.complete.destroy_all outs.to_json end
[ "def", "gather_outputs_from_work_units", "units", "=", "self", ".", "work_units", ".", "complete", "outs", "=", "self", ".", "work_units", ".", "complete", ".", "map", "{", "|", "u", "|", "u", ".", "parsed_output", "}", "self", ".", "work_units", ".", "complete", ".", "destroy_all", "outs", ".", "to_json", "end" ]
When the WorkUnits are all finished, gather all their outputs together before removing them from the database entirely. Returns their merged JSON.
[ "When", "the", "WorkUnits", "are", "all", "finished", "gather", "all", "their", "outputs", "together", "before", "removing", "them", "from", "the", "database", "entirely", ".", "Returns", "their", "merged", "JSON", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L183-L188
18,116
documentcloud/cloud-crowd
lib/cloud_crowd/models/job.rb
CloudCrowd.Job.queue_for_workers
def queue_for_workers(input=nil) input ||= JSON.parse(self.inputs) input.each {|i| WorkUnit.start(self, action, i, status) } self end
ruby
def queue_for_workers(input=nil) input ||= JSON.parse(self.inputs) input.each {|i| WorkUnit.start(self, action, i, status) } self end
[ "def", "queue_for_workers", "(", "input", "=", "nil", ")", "input", "||=", "JSON", ".", "parse", "(", "self", ".", "inputs", ")", "input", ".", "each", "{", "|", "i", "|", "WorkUnit", ".", "start", "(", "self", ",", "action", ",", "i", ",", "status", ")", "}", "self", "end" ]
When starting a new job, or moving to a new stage, split up the inputs into WorkUnits, and queue them. Workers will start picking them up right away.
[ "When", "starting", "a", "new", "job", "or", "moving", "to", "a", "new", "stage", "split", "up", "the", "inputs", "into", "WorkUnits", "and", "queue", "them", ".", "Workers", "will", "start", "picking", "them", "up", "right", "away", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/models/job.rb#L193-L197
18,117
documentcloud/cloud-crowd
lib/cloud_crowd/node.rb
CloudCrowd.Node.start
def start FileUtils.mkdir_p(CloudCrowd.log_path) if @daemon && !File.exists?(CloudCrowd.log_path) @server = Thin::Server.new('0.0.0.0', @port, self, :signals => false) @server.tag = 'cloud-crowd-node' @server.pid_file = CloudCrowd.pid_path('node.pid') @server.log_file = CloudCrowd.log_path('node.log') @server.daemonize if @daemon trap_signals asset_store @server_thread = Thread.new { @server.start } check_in(true) check_in_periodically monitor_system if @max_load || @min_memory @server_thread.join end
ruby
def start FileUtils.mkdir_p(CloudCrowd.log_path) if @daemon && !File.exists?(CloudCrowd.log_path) @server = Thin::Server.new('0.0.0.0', @port, self, :signals => false) @server.tag = 'cloud-crowd-node' @server.pid_file = CloudCrowd.pid_path('node.pid') @server.log_file = CloudCrowd.log_path('node.log') @server.daemonize if @daemon trap_signals asset_store @server_thread = Thread.new { @server.start } check_in(true) check_in_periodically monitor_system if @max_load || @min_memory @server_thread.join end
[ "def", "start", "FileUtils", ".", "mkdir_p", "(", "CloudCrowd", ".", "log_path", ")", "if", "@daemon", "&&", "!", "File", ".", "exists?", "(", "CloudCrowd", ".", "log_path", ")", "@server", "=", "Thin", "::", "Server", ".", "new", "(", "'0.0.0.0'", ",", "@port", ",", "self", ",", ":signals", "=>", "false", ")", "@server", ".", "tag", "=", "'cloud-crowd-node'", "@server", ".", "pid_file", "=", "CloudCrowd", ".", "pid_path", "(", "'node.pid'", ")", "@server", ".", "log_file", "=", "CloudCrowd", ".", "log_path", "(", "'node.log'", ")", "@server", ".", "daemonize", "if", "@daemon", "trap_signals", "asset_store", "@server_thread", "=", "Thread", ".", "new", "{", "@server", ".", "start", "}", "check_in", "(", "true", ")", "check_in_periodically", "monitor_system", "if", "@max_load", "||", "@min_memory", "@server_thread", ".", "join", "end" ]
When creating a node, specify the port it should run on. Starting up a Node registers with the central server and begins to listen for incoming WorkUnits.
[ "When", "creating", "a", "node", "specify", "the", "port", "it", "should", "run", "on", ".", "Starting", "up", "a", "Node", "registers", "with", "the", "central", "server", "and", "begins", "to", "listen", "for", "incoming", "WorkUnits", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L92-L106
18,118
documentcloud/cloud-crowd
lib/cloud_crowd/node.rb
CloudCrowd.Node.check_in
def check_in(critical=false) @central["/node/#{@id}"].put( :busy => @overloaded, :tag => @tag, :max_workers => CloudCrowd.config[:max_workers], :enabled_actions => @enabled_actions.join(',') ) rescue RestClient::Exception, Errno::ECONNREFUSED CloudCrowd.log "Failed to connect to the central server (#{@central.to_s})." raise SystemExit if critical end
ruby
def check_in(critical=false) @central["/node/#{@id}"].put( :busy => @overloaded, :tag => @tag, :max_workers => CloudCrowd.config[:max_workers], :enabled_actions => @enabled_actions.join(',') ) rescue RestClient::Exception, Errno::ECONNREFUSED CloudCrowd.log "Failed to connect to the central server (#{@central.to_s})." raise SystemExit if critical end
[ "def", "check_in", "(", "critical", "=", "false", ")", "@central", "[", "\"/node/#{@id}\"", "]", ".", "put", "(", ":busy", "=>", "@overloaded", ",", ":tag", "=>", "@tag", ",", ":max_workers", "=>", "CloudCrowd", ".", "config", "[", ":max_workers", "]", ",", ":enabled_actions", "=>", "@enabled_actions", ".", "join", "(", "','", ")", ")", "rescue", "RestClient", "::", "Exception", ",", "Errno", "::", "ECONNREFUSED", "CloudCrowd", ".", "log", "\"Failed to connect to the central server (#{@central.to_s}).\"", "raise", "SystemExit", "if", "critical", "end" ]
Checking in with the central server informs it of the location and configuration of this Node. If it can't check-in, there's no point in starting.
[ "Checking", "in", "with", "the", "central", "server", "informs", "it", "of", "the", "location", "and", "configuration", "of", "this", "Node", ".", "If", "it", "can", "t", "check", "-", "in", "there", "s", "no", "point", "in", "starting", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L111-L121
18,119
documentcloud/cloud-crowd
lib/cloud_crowd/node.rb
CloudCrowd.Node.free_memory
def free_memory case RUBY_PLATFORM when /darwin/ stats = `vm_stat` @mac_page_size ||= stats.match(SCRAPE_MAC_PAGE)[1].to_f / 1048576.0 stats.match(SCRAPE_MAC_MEMORY)[1].to_f * @mac_page_size when /linux/ `cat /proc/meminfo`.match(SCRAPE_LINUX_MEMORY)[1].to_f / 1024.0 else raise NotImplementedError, "'min_free_memory' is not yet implemented on your platform" end end
ruby
def free_memory case RUBY_PLATFORM when /darwin/ stats = `vm_stat` @mac_page_size ||= stats.match(SCRAPE_MAC_PAGE)[1].to_f / 1048576.0 stats.match(SCRAPE_MAC_MEMORY)[1].to_f * @mac_page_size when /linux/ `cat /proc/meminfo`.match(SCRAPE_LINUX_MEMORY)[1].to_f / 1024.0 else raise NotImplementedError, "'min_free_memory' is not yet implemented on your platform" end end
[ "def", "free_memory", "case", "RUBY_PLATFORM", "when", "/", "/", "stats", "=", "`", "`", "@mac_page_size", "||=", "stats", ".", "match", "(", "SCRAPE_MAC_PAGE", ")", "[", "1", "]", ".", "to_f", "/", "1048576.0", "stats", ".", "match", "(", "SCRAPE_MAC_MEMORY", ")", "[", "1", "]", ".", "to_f", "*", "@mac_page_size", "when", "/", "/", "`", "`", ".", "match", "(", "SCRAPE_LINUX_MEMORY", ")", "[", "1", "]", ".", "to_f", "/", "1024.0", "else", "raise", "NotImplementedError", ",", "\"'min_free_memory' is not yet implemented on your platform\"", "end", "end" ]
The current amount of free memory in megabytes.
[ "The", "current", "amount", "of", "free", "memory", "in", "megabytes", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L148-L159
18,120
documentcloud/cloud-crowd
lib/cloud_crowd/node.rb
CloudCrowd.Node.monitor_system
def monitor_system @monitor_thread = Thread.new do loop do was_overloaded = @overloaded @overloaded = overloaded? check_in if was_overloaded && !@overloaded sleep MONITOR_INTERVAL end end end
ruby
def monitor_system @monitor_thread = Thread.new do loop do was_overloaded = @overloaded @overloaded = overloaded? check_in if was_overloaded && !@overloaded sleep MONITOR_INTERVAL end end end
[ "def", "monitor_system", "@monitor_thread", "=", "Thread", ".", "new", "do", "loop", "do", "was_overloaded", "=", "@overloaded", "@overloaded", "=", "overloaded?", "check_in", "if", "was_overloaded", "&&", "!", "@overloaded", "sleep", "MONITOR_INTERVAL", "end", "end", "end" ]
Launch a monitoring thread that periodically checks the node's load average and the amount of free memory remaining. If we transition out of the overloaded state, let central know.
[ "Launch", "a", "monitoring", "thread", "that", "periodically", "checks", "the", "node", "s", "load", "average", "and", "the", "amount", "of", "free", "memory", "remaining", ".", "If", "we", "transition", "out", "of", "the", "overloaded", "state", "let", "central", "know", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L196-L205
18,121
documentcloud/cloud-crowd
lib/cloud_crowd/node.rb
CloudCrowd.Node.check_in_periodically
def check_in_periodically @check_in_thread = Thread.new do loop do check_on_workers reply = "" 1.upto(5).each do | attempt_number | # sleep for an ever increasing amount of time to prevent overloading the server sleep CHECK_IN_INTERVAL * attempt_number reply = check_in # if we did not receive a reply, the server has went away; it # will reply with an empty string if the check-in succeeds if reply.nil? CloudCrowd.log "Failed on attempt ##{attempt_number} to check in with server" else break end end if reply.nil? CloudCrowd.log "Giving up after repeated attempts to contact server" raise SystemExit end end end end
ruby
def check_in_periodically @check_in_thread = Thread.new do loop do check_on_workers reply = "" 1.upto(5).each do | attempt_number | # sleep for an ever increasing amount of time to prevent overloading the server sleep CHECK_IN_INTERVAL * attempt_number reply = check_in # if we did not receive a reply, the server has went away; it # will reply with an empty string if the check-in succeeds if reply.nil? CloudCrowd.log "Failed on attempt ##{attempt_number} to check in with server" else break end end if reply.nil? CloudCrowd.log "Giving up after repeated attempts to contact server" raise SystemExit end end end end
[ "def", "check_in_periodically", "@check_in_thread", "=", "Thread", ".", "new", "do", "loop", "do", "check_on_workers", "reply", "=", "\"\"", "1", ".", "upto", "(", "5", ")", ".", "each", "do", "|", "attempt_number", "|", "# sleep for an ever increasing amount of time to prevent overloading the server", "sleep", "CHECK_IN_INTERVAL", "*", "attempt_number", "reply", "=", "check_in", "# if we did not receive a reply, the server has went away; it", "# will reply with an empty string if the check-in succeeds", "if", "reply", ".", "nil?", "CloudCrowd", ".", "log", "\"Failed on attempt ##{attempt_number} to check in with server\"", "else", "break", "end", "end", "if", "reply", ".", "nil?", "CloudCrowd", ".", "log", "\"Giving up after repeated attempts to contact server\"", "raise", "SystemExit", "end", "end", "end", "end" ]
If communication is interrupted for external reasons, the central server will assume that the node has gone down. Checking in will let central know it's still online.
[ "If", "communication", "is", "interrupted", "for", "external", "reasons", "the", "central", "server", "will", "assume", "that", "the", "node", "has", "gone", "down", ".", "Checking", "in", "will", "let", "central", "know", "it", "s", "still", "online", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L210-L233
18,122
documentcloud/cloud-crowd
lib/cloud_crowd/node.rb
CloudCrowd.Node.trap_signals
def trap_signals Signal.trap('QUIT') { shut_down } Signal.trap('INT') { shut_down } Signal.trap('TERM') { shut_down } end
ruby
def trap_signals Signal.trap('QUIT') { shut_down } Signal.trap('INT') { shut_down } Signal.trap('TERM') { shut_down } end
[ "def", "trap_signals", "Signal", ".", "trap", "(", "'QUIT'", ")", "{", "shut_down", "}", "Signal", ".", "trap", "(", "'INT'", ")", "{", "shut_down", "}", "Signal", ".", "trap", "(", "'TERM'", ")", "{", "shut_down", "}", "end" ]
Trap exit signals in order to shut down cleanly.
[ "Trap", "exit", "signals", "in", "order", "to", "shut", "down", "cleanly", "." ]
a66172eabc6cb526b27be2bb821e2ea4258c82d4
https://github.com/documentcloud/cloud-crowd/blob/a66172eabc6cb526b27be2bb821e2ea4258c82d4/lib/cloud_crowd/node.rb#L236-L240
18,123
rob-murray/jekyll-twitter-plugin
lib/jekyll-twitter-plugin.rb
TwitterJekyll.ApiClient.fetch
def fetch(api_request) uri = api_request.to_uri response = Net::HTTP.start(uri.host, use_ssl: api_request.ssl?) do |http| http.read_timeout = 5 http.open_timeout = 5 http.get uri.request_uri, REQUEST_HEADERS end handle_response(api_request, response) rescue Timeout::Error => e ErrorResponse.new(api_request, e.class.name).to_h end
ruby
def fetch(api_request) uri = api_request.to_uri response = Net::HTTP.start(uri.host, use_ssl: api_request.ssl?) do |http| http.read_timeout = 5 http.open_timeout = 5 http.get uri.request_uri, REQUEST_HEADERS end handle_response(api_request, response) rescue Timeout::Error => e ErrorResponse.new(api_request, e.class.name).to_h end
[ "def", "fetch", "(", "api_request", ")", "uri", "=", "api_request", ".", "to_uri", "response", "=", "Net", "::", "HTTP", ".", "start", "(", "uri", ".", "host", ",", "use_ssl", ":", "api_request", ".", "ssl?", ")", "do", "|", "http", "|", "http", ".", "read_timeout", "=", "5", "http", ".", "open_timeout", "=", "5", "http", ".", "get", "uri", ".", "request_uri", ",", "REQUEST_HEADERS", "end", "handle_response", "(", "api_request", ",", "response", ")", "rescue", "Timeout", "::", "Error", "=>", "e", "ErrorResponse", ".", "new", "(", "api_request", ",", "e", ".", "class", ".", "name", ")", ".", "to_h", "end" ]
Perform API request; return hash with html content
[ "Perform", "API", "request", ";", "return", "hash", "with", "html", "content" ]
6f6aa9466c9da5effa72ff24730599bc574285bc
https://github.com/rob-murray/jekyll-twitter-plugin/blob/6f6aa9466c9da5effa72ff24730599bc574285bc/lib/jekyll-twitter-plugin.rb#L71-L83
18,124
rob-murray/jekyll-twitter-plugin
lib/jekyll-twitter-plugin.rb
TwitterJekyll.TwitterTag.live_response
def live_response if response = api_client.fetch(@api_request) cache.write(@api_request.cache_key, response) build_response(response) end end
ruby
def live_response if response = api_client.fetch(@api_request) cache.write(@api_request.cache_key, response) build_response(response) end end
[ "def", "live_response", "if", "response", "=", "api_client", ".", "fetch", "(", "@api_request", ")", "cache", ".", "write", "(", "@api_request", ".", "cache_key", ",", "response", ")", "build_response", "(", "response", ")", "end", "end" ]
Return response from API and write to cache @api private
[ "Return", "response", "from", "API", "and", "write", "to", "cache" ]
6f6aa9466c9da5effa72ff24730599bc574285bc
https://github.com/rob-murray/jekyll-twitter-plugin/blob/6f6aa9466c9da5effa72ff24730599bc574285bc/lib/jekyll-twitter-plugin.rb#L188-L193
18,125
rob-murray/jekyll-twitter-plugin
lib/jekyll-twitter-plugin.rb
TwitterJekyll.TwitterTag.parse_params
def parse_params(params) args = params.split(/\s+/).map(&:strip) invalid_args!(args) unless args.any? if args[0].to_s == OEMBED_ARG # TODO: remove after deprecation cycle arguments_deprecation_warning(args) args.shift end url, *api_args = args ApiRequest.new(url, parse_args(api_args)) end
ruby
def parse_params(params) args = params.split(/\s+/).map(&:strip) invalid_args!(args) unless args.any? if args[0].to_s == OEMBED_ARG # TODO: remove after deprecation cycle arguments_deprecation_warning(args) args.shift end url, *api_args = args ApiRequest.new(url, parse_args(api_args)) end
[ "def", "parse_params", "(", "params", ")", "args", "=", "params", ".", "split", "(", "/", "\\s", "/", ")", ".", "map", "(", ":strip", ")", "invalid_args!", "(", "args", ")", "unless", "args", ".", "any?", "if", "args", "[", "0", "]", ".", "to_s", "==", "OEMBED_ARG", "# TODO: remove after deprecation cycle", "arguments_deprecation_warning", "(", "args", ")", "args", ".", "shift", "end", "url", ",", "*", "api_args", "=", "args", "ApiRequest", ".", "new", "(", "url", ",", "parse_args", "(", "api_args", ")", ")", "end" ]
Return an `ApiRequest` with the url and arguments @api private
[ "Return", "an", "ApiRequest", "with", "the", "url", "and", "arguments" ]
6f6aa9466c9da5effa72ff24730599bc574285bc
https://github.com/rob-murray/jekyll-twitter-plugin/blob/6f6aa9466c9da5effa72ff24730599bc574285bc/lib/jekyll-twitter-plugin.rb#L204-L215
18,126
michaelherold/interactor-contracts
lib/interactor/contracts.rb
Interactor.Contracts.enforce_contracts
def enforce_contracts(contracts) outcome = contracts.call(context) unless outcome.success? contract.consequences.each do |handler| instance_exec(outcome.breaches, &handler) end end end
ruby
def enforce_contracts(contracts) outcome = contracts.call(context) unless outcome.success? contract.consequences.each do |handler| instance_exec(outcome.breaches, &handler) end end end
[ "def", "enforce_contracts", "(", "contracts", ")", "outcome", "=", "contracts", ".", "call", "(", "context", ")", "unless", "outcome", ".", "success?", "contract", ".", "consequences", ".", "each", "do", "|", "handler", "|", "instance_exec", "(", "outcome", ".", "breaches", ",", "handler", ")", "end", "end", "end" ]
Checks for a breach of contract and applies consequences for a breach @api private @param [#call] contracts a callable object @return [void]
[ "Checks", "for", "a", "breach", "of", "contract", "and", "applies", "consequences", "for", "a", "breach" ]
75b7a98e89d8bc4682ed8fd71143437f00a83496
https://github.com/michaelherold/interactor-contracts/blob/75b7a98e89d8bc4682ed8fd71143437f00a83496/lib/interactor/contracts.rb#L37-L45
18,127
liveh2o/active_remote
lib/active_remote/persistence.rb
ActiveRemote.Persistence.remote
def remote(endpoint, request_args = scope_key_hash) response = remote_call(endpoint, request_args) assign_attributes_from_rpc(response) success? end
ruby
def remote(endpoint, request_args = scope_key_hash) response = remote_call(endpoint, request_args) assign_attributes_from_rpc(response) success? end
[ "def", "remote", "(", "endpoint", ",", "request_args", "=", "scope_key_hash", ")", "response", "=", "remote_call", "(", "endpoint", ",", "request_args", ")", "assign_attributes_from_rpc", "(", "response", ")", "success?", "end" ]
Executes a remote call on the current object and serializes it's attributes and errors from the response. Defaults request args to the scope key hash (e.g., { guid: 'ABC-123' }) when none are given. Returns false if the response contained errors; otherwise, returns true.
[ "Executes", "a", "remote", "call", "on", "the", "current", "object", "and", "serializes", "it", "s", "attributes", "and", "errors", "from", "the", "response", "." ]
5939c8e9f8515d8600d59ab26932a0de31076674
https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/persistence.rb#L167-L172
18,128
liveh2o/active_remote
lib/active_remote/attributes.rb
ActiveRemote.Attributes.read_attribute
def read_attribute(name) name = name.to_s if respond_to?(name) attribute(name) else raise ::ActiveRemote::UnknownAttributeError, "unknown attribute: #{name}" end end
ruby
def read_attribute(name) name = name.to_s if respond_to?(name) attribute(name) else raise ::ActiveRemote::UnknownAttributeError, "unknown attribute: #{name}" end end
[ "def", "read_attribute", "(", "name", ")", "name", "=", "name", ".", "to_s", "if", "respond_to?", "(", "name", ")", "attribute", "(", "name", ")", "else", "raise", "::", "ActiveRemote", "::", "UnknownAttributeError", ",", "\"unknown attribute: #{name}\"", "end", "end" ]
Read attribute from the attributes hash
[ "Read", "attribute", "from", "the", "attributes", "hash" ]
5939c8e9f8515d8600d59ab26932a0de31076674
https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/attributes.rb#L39-L47
18,129
liveh2o/active_remote
lib/active_remote/attributes.rb
ActiveRemote.Attributes.write_attribute
def write_attribute(name, value) name = name.to_s if respond_to?("#{name}=") __send__("attribute=", name, value) else raise ::ActiveRemote::UnknownAttributeError, "unknown attribute: #{name}" end end
ruby
def write_attribute(name, value) name = name.to_s if respond_to?("#{name}=") __send__("attribute=", name, value) else raise ::ActiveRemote::UnknownAttributeError, "unknown attribute: #{name}" end end
[ "def", "write_attribute", "(", "name", ",", "value", ")", "name", "=", "name", ".", "to_s", "if", "respond_to?", "(", "\"#{name}=\"", ")", "__send__", "(", "\"attribute=\"", ",", "name", ",", "value", ")", "else", "raise", "::", "ActiveRemote", "::", "UnknownAttributeError", ",", "\"unknown attribute: #{name}\"", "end", "end" ]
Update an attribute in the attributes hash
[ "Update", "an", "attribute", "in", "the", "attributes", "hash" ]
5939c8e9f8515d8600d59ab26932a0de31076674
https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/attributes.rb#L52-L60
18,130
liveh2o/active_remote
lib/active_remote/serialization.rb
ActiveRemote.Serialization.add_errors
def add_errors(errors) errors.each do |error| if error.respond_to?(:message) self.errors.add(error.field, error.message) elsif error.respond_to?(:messages) error.messages.each do |message| self.errors.add(error.field, message) end end end end
ruby
def add_errors(errors) errors.each do |error| if error.respond_to?(:message) self.errors.add(error.field, error.message) elsif error.respond_to?(:messages) error.messages.each do |message| self.errors.add(error.field, message) end end end end
[ "def", "add_errors", "(", "errors", ")", "errors", ".", "each", "do", "|", "error", "|", "if", "error", ".", "respond_to?", "(", ":message", ")", "self", ".", "errors", ".", "add", "(", "error", ".", "field", ",", "error", ".", "message", ")", "elsif", "error", ".", "respond_to?", "(", ":messages", ")", "error", ".", "messages", ".", "each", "do", "|", "message", "|", "self", ".", "errors", ".", "add", "(", "error", ".", "field", ",", "message", ")", "end", "end", "end", "end" ]
Add the given errors to our internal errors list ====Examples response = remote_call(:action_that_returns_errors, { :stuff => 'foo' }) add_errors(response.errors)
[ "Add", "the", "given", "errors", "to", "our", "internal", "errors", "list" ]
5939c8e9f8515d8600d59ab26932a0de31076674
https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/serialization.rb#L35-L45
18,131
liveh2o/active_remote
lib/active_remote/integration.rb
ActiveRemote.Integration.cache_key
def cache_key case when new_record? then "#{self.class.name.underscore}/new" when ::ActiveRemote.config.default_cache_key_updated_at? && (timestamp = self[:updated_at]) then timestamp = timestamp.utc.to_s(self.class.cache_timestamp_format) "#{self.class.name.underscore}/#{self.to_param}-#{timestamp}" else "#{self.class.name.underscore}/#{self.to_param}" end end
ruby
def cache_key case when new_record? then "#{self.class.name.underscore}/new" when ::ActiveRemote.config.default_cache_key_updated_at? && (timestamp = self[:updated_at]) then timestamp = timestamp.utc.to_s(self.class.cache_timestamp_format) "#{self.class.name.underscore}/#{self.to_param}-#{timestamp}" else "#{self.class.name.underscore}/#{self.to_param}" end end
[ "def", "cache_key", "case", "when", "new_record?", "then", "\"#{self.class.name.underscore}/new\"", "when", "::", "ActiveRemote", ".", "config", ".", "default_cache_key_updated_at?", "&&", "(", "timestamp", "=", "self", "[", ":updated_at", "]", ")", "then", "timestamp", "=", "timestamp", ".", "utc", ".", "to_s", "(", "self", ".", "class", ".", "cache_timestamp_format", ")", "\"#{self.class.name.underscore}/#{self.to_param}-#{timestamp}\"", "else", "\"#{self.class.name.underscore}/#{self.to_param}\"", "end", "end" ]
Returns a cache key that can be used to identify this record. ==== Examples Product.new.cache_key # => "products/new" Person.search(:guid => "derp-5").cache_key # => "people/derp-5-20071224150000" (include updated_at) Product.search(:guid => "derp-5").cache_key # => "products/derp-5"
[ "Returns", "a", "cache", "key", "that", "can", "be", "used", "to", "identify", "this", "record", "." ]
5939c8e9f8515d8600d59ab26932a0de31076674
https://github.com/liveh2o/active_remote/blob/5939c8e9f8515d8600d59ab26932a0de31076674/lib/active_remote/integration.rb#L39-L49
18,132
msg7086/rb1drv
lib/rb1drv/onedrive_file.rb
Rb1drv.OneDriveFile.save_as
def save_as(target_name=nil, overwrite: false, resume: true, &block) target_name ||= @name tmpfile = "#{target_name}.incomplete" return if !overwrite && File.exist?(target_name) if resume && File.size(tmpfile) > 0 from = File.size(tmpfile) len = @size - from fmode = 'ab' headers = { 'Range': "bytes=#{from}-" } else from = 0 len = @size fmode = 'wb' headers = {} end yield :new_segment, file: target_name, from: from if block_given? File.open(tmpfile, mode: fmode, external_encoding: Encoding::BINARY) do |f| Excon.get download_url, headers: headers, response_block: ->(chunk, remaining_bytes, total_bytes) do f.write(chunk) yield :progress, file: target_name, from: from, progress: total_bytes - remaining_bytes, total: total_bytes if block_given? end end yield :finish_segment, file: target_name if block_given? FileUtils.mv(tmpfile, filename) end
ruby
def save_as(target_name=nil, overwrite: false, resume: true, &block) target_name ||= @name tmpfile = "#{target_name}.incomplete" return if !overwrite && File.exist?(target_name) if resume && File.size(tmpfile) > 0 from = File.size(tmpfile) len = @size - from fmode = 'ab' headers = { 'Range': "bytes=#{from}-" } else from = 0 len = @size fmode = 'wb' headers = {} end yield :new_segment, file: target_name, from: from if block_given? File.open(tmpfile, mode: fmode, external_encoding: Encoding::BINARY) do |f| Excon.get download_url, headers: headers, response_block: ->(chunk, remaining_bytes, total_bytes) do f.write(chunk) yield :progress, file: target_name, from: from, progress: total_bytes - remaining_bytes, total: total_bytes if block_given? end end yield :finish_segment, file: target_name if block_given? FileUtils.mv(tmpfile, filename) end
[ "def", "save_as", "(", "target_name", "=", "nil", ",", "overwrite", ":", "false", ",", "resume", ":", "true", ",", "&", "block", ")", "target_name", "||=", "@name", "tmpfile", "=", "\"#{target_name}.incomplete\"", "return", "if", "!", "overwrite", "&&", "File", ".", "exist?", "(", "target_name", ")", "if", "resume", "&&", "File", ".", "size", "(", "tmpfile", ")", ">", "0", "from", "=", "File", ".", "size", "(", "tmpfile", ")", "len", "=", "@size", "-", "from", "fmode", "=", "'ab'", "headers", "=", "{", "'Range'", ":", "\"bytes=#{from}-\"", "}", "else", "from", "=", "0", "len", "=", "@size", "fmode", "=", "'wb'", "headers", "=", "{", "}", "end", "yield", ":new_segment", ",", "file", ":", "target_name", ",", "from", ":", "from", "if", "block_given?", "File", ".", "open", "(", "tmpfile", ",", "mode", ":", "fmode", ",", "external_encoding", ":", "Encoding", "::", "BINARY", ")", "do", "|", "f", "|", "Excon", ".", "get", "download_url", ",", "headers", ":", "headers", ",", "response_block", ":", "->", "(", "chunk", ",", "remaining_bytes", ",", "total_bytes", ")", "do", "f", ".", "write", "(", "chunk", ")", "yield", ":progress", ",", "file", ":", "target_name", ",", "from", ":", "from", ",", "progress", ":", "total_bytes", "-", "remaining_bytes", ",", "total", ":", "total_bytes", "if", "block_given?", "end", "end", "yield", ":finish_segment", ",", "file", ":", "target_name", "if", "block_given?", "FileUtils", ".", "mv", "(", "tmpfile", ",", "filename", ")", "end" ]
Saves current remote file as local file. Unfinished download is stored as +target_name.incomplete+ and renamed upon completion. @param target_name [String] desired local filename, a relative path to current directory or an absolute path @param overwrite [Boolean] whether to overwrite local file, or skip this @param resume [Boolean] whether to resume an unfinished download, or start over anyway @yield [event, status] for receive progress notification @yieldparam event [Symbol] event of this notification @yieldparam status [{Symbol => String,Integer}] details
[ "Saves", "current", "remote", "file", "as", "local", "file", "." ]
090429252cd0a0d13bbbdfb2bffdf99e3921c893
https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_file.rb#L30-L59
18,133
msg7086/rb1drv
lib/rb1drv/onedrive_file.rb
Rb1drv.OneDriveFile.set_mtime
def set_mtime(time) attempt = 0 OneDriveFile.new(@od, @od.request(api_path, {fileSystemInfo: {lastModifiedDateTime: time.utc.iso8601}}, :patch)) rescue sleep 10 attempt += 1 retry if attempt <= 3 end
ruby
def set_mtime(time) attempt = 0 OneDriveFile.new(@od, @od.request(api_path, {fileSystemInfo: {lastModifiedDateTime: time.utc.iso8601}}, :patch)) rescue sleep 10 attempt += 1 retry if attempt <= 3 end
[ "def", "set_mtime", "(", "time", ")", "attempt", "=", "0", "OneDriveFile", ".", "new", "(", "@od", ",", "@od", ".", "request", "(", "api_path", ",", "{", "fileSystemInfo", ":", "{", "lastModifiedDateTime", ":", "time", ".", "utc", ".", "iso8601", "}", "}", ",", ":patch", ")", ")", "rescue", "sleep", "10", "attempt", "+=", "1", "retry", "if", "attempt", "<=", "3", "end" ]
Change last modified time for a remote file. NOTICE: OneDrive by default keeps multiple history version for this operation. NOTICE: You must turn off versioning to prevent multiple counts on disk quota. 3 attempts will be made due to delay after a file upload. @param time [Time] desired last modified time @return [OneDriveFile] new file object returned by API
[ "Change", "last", "modified", "time", "for", "a", "remote", "file", "." ]
090429252cd0a0d13bbbdfb2bffdf99e3921c893
https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_file.rb#L70-L77
18,134
msg7086/rb1drv
lib/rb1drv.rb
Rb1drv.OneDrive.request
def request(uri, data=nil, verb=:post) @logger.info(uri) if @logger auth_check query = { path: File.join('v1.0/me/', URI.escape(uri)), headers: { 'Authorization': "Bearer #{@access_token.token}" } } if data query[:body] = JSON.generate(data) query[:headers]['Content-Type'] = 'application/json' @logger.info(query[:body]) if @logger verb = :post unless [:post, :put, :patch, :delete].include?(verb) response = @conn.send(verb, query) else response = @conn.get(query) end JSON.parse(response.body) end
ruby
def request(uri, data=nil, verb=:post) @logger.info(uri) if @logger auth_check query = { path: File.join('v1.0/me/', URI.escape(uri)), headers: { 'Authorization': "Bearer #{@access_token.token}" } } if data query[:body] = JSON.generate(data) query[:headers]['Content-Type'] = 'application/json' @logger.info(query[:body]) if @logger verb = :post unless [:post, :put, :patch, :delete].include?(verb) response = @conn.send(verb, query) else response = @conn.get(query) end JSON.parse(response.body) end
[ "def", "request", "(", "uri", ",", "data", "=", "nil", ",", "verb", "=", ":post", ")", "@logger", ".", "info", "(", "uri", ")", "if", "@logger", "auth_check", "query", "=", "{", "path", ":", "File", ".", "join", "(", "'v1.0/me/'", ",", "URI", ".", "escape", "(", "uri", ")", ")", ",", "headers", ":", "{", "'Authorization'", ":", "\"Bearer #{@access_token.token}\"", "}", "}", "if", "data", "query", "[", ":body", "]", "=", "JSON", ".", "generate", "(", "data", ")", "query", "[", ":headers", "]", "[", "'Content-Type'", "]", "=", "'application/json'", "@logger", ".", "info", "(", "query", "[", ":body", "]", ")", "if", "@logger", "verb", "=", ":post", "unless", "[", ":post", ",", ":put", ",", ":patch", ",", ":delete", "]", ".", "include?", "(", "verb", ")", "response", "=", "@conn", ".", "send", "(", "verb", ",", "query", ")", "else", "response", "=", "@conn", ".", "get", "(", "query", ")", "end", "JSON", ".", "parse", "(", "response", ".", "body", ")", "end" ]
Instanciates with app id and secret. Issues requests to API endpoint. @param uri [String] relative path of the API @param data [Hash] JSON data to be post @param verb [Symbol] HTTP request verb if data is given @return [Hash] response from API.
[ "Instanciates", "with", "app", "id", "and", "secret", ".", "Issues", "requests", "to", "API", "endpoint", "." ]
090429252cd0a0d13bbbdfb2bffdf99e3921c893
https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv.rb#L31-L50
18,135
msg7086/rb1drv
lib/rb1drv/onedrive_dir.rb
Rb1drv.OneDriveDir.get_child
def get_child(path) children.find { |child| child.name == path } || OneDrive404.new end
ruby
def get_child(path) children.find { |child| child.name == path } || OneDrive404.new end
[ "def", "get_child", "(", "path", ")", "children", ".", "find", "{", "|", "child", "|", "child", ".", "name", "==", "path", "}", "||", "OneDrive404", ".", "new", "end" ]
Get a child object by name inside current directory. @param path [String] name of a child @return [OneDriveDir,OneDriveFile,OneDrive404] the drive item you asked
[ "Get", "a", "child", "object", "by", "name", "inside", "current", "directory", "." ]
090429252cd0a0d13bbbdfb2bffdf99e3921c893
https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_dir.rb#L30-L32
18,136
msg7086/rb1drv
lib/rb1drv/onedrive_dir.rb
Rb1drv.OneDriveDir.mkdir
def mkdir(name) return self if name == '.' name = name[1..-1] if name[0] == '/' newdir, *remainder = name.split('/') subdir = get(newdir) unless subdir.dir? result = @od.request("#{api_path}/children", name: newdir, folder: {}, '@microsoft.graph.conflictBehavior': 'rename' ) subdir = OneDriveDir.new(@od, result) end remainder.any? ? subdir.mkdir(remainder.join('/')) : subdir end
ruby
def mkdir(name) return self if name == '.' name = name[1..-1] if name[0] == '/' newdir, *remainder = name.split('/') subdir = get(newdir) unless subdir.dir? result = @od.request("#{api_path}/children", name: newdir, folder: {}, '@microsoft.graph.conflictBehavior': 'rename' ) subdir = OneDriveDir.new(@od, result) end remainder.any? ? subdir.mkdir(remainder.join('/')) : subdir end
[ "def", "mkdir", "(", "name", ")", "return", "self", "if", "name", "==", "'.'", "name", "=", "name", "[", "1", "..", "-", "1", "]", "if", "name", "[", "0", "]", "==", "'/'", "newdir", ",", "*", "remainder", "=", "name", ".", "split", "(", "'/'", ")", "subdir", "=", "get", "(", "newdir", ")", "unless", "subdir", ".", "dir?", "result", "=", "@od", ".", "request", "(", "\"#{api_path}/children\"", ",", "name", ":", "newdir", ",", "folder", ":", "{", "}", ",", "'@microsoft.graph.conflictBehavior'", ":", "'rename'", ")", "subdir", "=", "OneDriveDir", ".", "new", "(", "@od", ",", "result", ")", "end", "remainder", ".", "any?", "?", "subdir", ".", "mkdir", "(", "remainder", ".", "join", "(", "'/'", ")", ")", ":", "subdir", "end" ]
Recursively creates empty directories. @param name [String] directories you'd like to create @return [OneDriveDir] the directory you created
[ "Recursively", "creates", "empty", "directories", "." ]
090429252cd0a0d13bbbdfb2bffdf99e3921c893
https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_dir.rb#L71-L85
18,137
msg7086/rb1drv
lib/rb1drv/onedrive_dir.rb
Rb1drv.OneDriveDir.upload_simple
def upload_simple(filename, overwrite:, target_name:) target_file = get(target_name) exist = target_file.file? return if exist && !overwrite path = nil if exist path = "#{target_file.api_path}/content" else path = "#{api_path}:/#{target_name}:/content" end query = { path: File.join('v1.0/me/', path), headers: { 'Authorization': "Bearer #{@od.access_token.token}", 'Content-Type': 'application/octet-stream' }, body: File.read(filename) } result = @od.conn.put(query) result = JSON.parse(result.body) file = OneDriveFile.new(@od, result) file.set_mtime(File.mtime(filename)) end
ruby
def upload_simple(filename, overwrite:, target_name:) target_file = get(target_name) exist = target_file.file? return if exist && !overwrite path = nil if exist path = "#{target_file.api_path}/content" else path = "#{api_path}:/#{target_name}:/content" end query = { path: File.join('v1.0/me/', path), headers: { 'Authorization': "Bearer #{@od.access_token.token}", 'Content-Type': 'application/octet-stream' }, body: File.read(filename) } result = @od.conn.put(query) result = JSON.parse(result.body) file = OneDriveFile.new(@od, result) file.set_mtime(File.mtime(filename)) end
[ "def", "upload_simple", "(", "filename", ",", "overwrite", ":", ",", "target_name", ":", ")", "target_file", "=", "get", "(", "target_name", ")", "exist", "=", "target_file", ".", "file?", "return", "if", "exist", "&&", "!", "overwrite", "path", "=", "nil", "if", "exist", "path", "=", "\"#{target_file.api_path}/content\"", "else", "path", "=", "\"#{api_path}:/#{target_name}:/content\"", "end", "query", "=", "{", "path", ":", "File", ".", "join", "(", "'v1.0/me/'", ",", "path", ")", ",", "headers", ":", "{", "'Authorization'", ":", "\"Bearer #{@od.access_token.token}\"", ",", "'Content-Type'", ":", "'application/octet-stream'", "}", ",", "body", ":", "File", ".", "read", "(", "filename", ")", "}", "result", "=", "@od", ".", "conn", ".", "put", "(", "query", ")", "result", "=", "JSON", ".", "parse", "(", "result", ".", "body", ")", "file", "=", "OneDriveFile", ".", "new", "(", "@od", ",", "result", ")", "file", ".", "set_mtime", "(", "File", ".", "mtime", "(", "filename", ")", ")", "end" ]
Uploads a local file into current remote directory using simple upload mode. @return [OneDriveFile,nil] uploaded file
[ "Uploads", "a", "local", "file", "into", "current", "remote", "directory", "using", "simple", "upload", "mode", "." ]
090429252cd0a0d13bbbdfb2bffdf99e3921c893
https://github.com/msg7086/rb1drv/blob/090429252cd0a0d13bbbdfb2bffdf99e3921c893/lib/rb1drv/onedrive_dir.rb#L206-L229
18,138
jugyo/eeepub
lib/eeepub/ocf.rb
EeePub.OCF.save
def save(output_path) output_path = File.expand_path(output_path) create_epub do mimetype = Zip::ZipOutputStream::open(output_path) do |os| os.put_next_entry("mimetype", nil, nil, Zip::ZipEntry::STORED, Zlib::NO_COMPRESSION) os << "application/epub+zip" end zipfile = Zip::ZipFile.open(output_path) Dir.glob('**/*').each do |path| zipfile.add(path, path) end zipfile.commit end FileUtils.remove_entry_secure dir end
ruby
def save(output_path) output_path = File.expand_path(output_path) create_epub do mimetype = Zip::ZipOutputStream::open(output_path) do |os| os.put_next_entry("mimetype", nil, nil, Zip::ZipEntry::STORED, Zlib::NO_COMPRESSION) os << "application/epub+zip" end zipfile = Zip::ZipFile.open(output_path) Dir.glob('**/*').each do |path| zipfile.add(path, path) end zipfile.commit end FileUtils.remove_entry_secure dir end
[ "def", "save", "(", "output_path", ")", "output_path", "=", "File", ".", "expand_path", "(", "output_path", ")", "create_epub", "do", "mimetype", "=", "Zip", "::", "ZipOutputStream", "::", "open", "(", "output_path", ")", "do", "|", "os", "|", "os", ".", "put_next_entry", "(", "\"mimetype\"", ",", "nil", ",", "nil", ",", "Zip", "::", "ZipEntry", "::", "STORED", ",", "Zlib", "::", "NO_COMPRESSION", ")", "os", "<<", "\"application/epub+zip\"", "end", "zipfile", "=", "Zip", "::", "ZipFile", ".", "open", "(", "output_path", ")", "Dir", ".", "glob", "(", "'**/*'", ")", ".", "each", "do", "|", "path", "|", "zipfile", ".", "add", "(", "path", ",", "path", ")", "end", "zipfile", ".", "commit", "end", "FileUtils", ".", "remove_entry_secure", "dir", "end" ]
Save as OCF @param [String] output_path the output file path of ePub
[ "Save", "as", "OCF" ]
e120406d599d1ca27927e106c02caf3e14ff3976
https://github.com/jugyo/eeepub/blob/e120406d599d1ca27927e106c02caf3e14ff3976/lib/eeepub/ocf.rb#L91-L106
18,139
jugyo/eeepub
lib/eeepub/container_item.rb
EeePub.ContainerItem.to_xml
def to_xml out = "" builder = Builder::XmlMarkup.new(:target => out, :indent => 2) builder.instruct! build_xml(builder) out end
ruby
def to_xml out = "" builder = Builder::XmlMarkup.new(:target => out, :indent => 2) builder.instruct! build_xml(builder) out end
[ "def", "to_xml", "out", "=", "\"\"", "builder", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":target", "=>", "out", ",", ":indent", "=>", "2", ")", "builder", ".", "instruct!", "build_xml", "(", "builder", ")", "out", "end" ]
Convert to xml of container item @return [String] the xml of container item
[ "Convert", "to", "xml", "of", "container", "item" ]
e120406d599d1ca27927e106c02caf3e14ff3976
https://github.com/jugyo/eeepub/blob/e120406d599d1ca27927e106c02caf3e14ff3976/lib/eeepub/container_item.rb#L51-L57
18,140
jugyo/eeepub
lib/eeepub/container_item.rb
EeePub.ContainerItem.convert_to_xml_attributes
def convert_to_xml_attributes(hash) result = {} hash.each do |k, v| key = k.to_s.gsub('_', '-').to_sym result[key] = v end result end
ruby
def convert_to_xml_attributes(hash) result = {} hash.each do |k, v| key = k.to_s.gsub('_', '-').to_sym result[key] = v end result end
[ "def", "convert_to_xml_attributes", "(", "hash", ")", "result", "=", "{", "}", "hash", ".", "each", "do", "|", "k", ",", "v", "|", "key", "=", "k", ".", "to_s", ".", "gsub", "(", "'_'", ",", "'-'", ")", ".", "to_sym", "result", "[", "key", "]", "=", "v", "end", "result", "end" ]
Convert options for xml attributes @param [Hash<Symbol, Object>] hash the hash of symbols and objects for xml attributes @return [Hash<String, Object>] the options for xml attributes
[ "Convert", "options", "for", "xml", "attributes" ]
e120406d599d1ca27927e106c02caf3e14ff3976
https://github.com/jugyo/eeepub/blob/e120406d599d1ca27927e106c02caf3e14ff3976/lib/eeepub/container_item.rb#L99-L106
18,141
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.witness_commitment
def witness_commitment return nil unless coinbase_tx? outputs.each do |output| commitment = output.script_pubkey.witness_commitment return commitment if commitment end nil end
ruby
def witness_commitment return nil unless coinbase_tx? outputs.each do |output| commitment = output.script_pubkey.witness_commitment return commitment if commitment end nil end
[ "def", "witness_commitment", "return", "nil", "unless", "coinbase_tx?", "outputs", ".", "each", "do", "|", "output", "|", "commitment", "=", "output", ".", "script_pubkey", ".", "witness_commitment", "return", "commitment", "if", "commitment", "end", "nil", "end" ]
get the witness commitment of coinbase tx. if this tx does not coinbase or not have commitment, return nil.
[ "get", "the", "witness", "commitment", "of", "coinbase", "tx", ".", "if", "this", "tx", "does", "not", "coinbase", "or", "not", "have", "commitment", "return", "nil", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L94-L101
18,142
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.serialize_old_format
def serialize_old_format buf = [version].pack('V') buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join buf << [lock_time].pack('V') buf end
ruby
def serialize_old_format buf = [version].pack('V') buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join buf << [lock_time].pack('V') buf end
[ "def", "serialize_old_format", "buf", "=", "[", "version", "]", ".", "pack", "(", "'V'", ")", "buf", "<<", "Bitcoin", ".", "pack_var_int", "(", "inputs", ".", "length", ")", "<<", "inputs", ".", "map", "(", ":to_payload", ")", ".", "join", "buf", "<<", "Bitcoin", ".", "pack_var_int", "(", "outputs", ".", "length", ")", "<<", "outputs", ".", "map", "(", ":to_payload", ")", ".", "join", "buf", "<<", "[", "lock_time", "]", ".", "pack", "(", "'V'", ")", "buf", "end" ]
serialize tx with old tx format
[ "serialize", "tx", "with", "old", "tx", "format" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L120-L126
18,143
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.standard?
def standard? return false if version > MAX_STANDARD_VERSION return false if weight > MAX_STANDARD_TX_WEIGHT inputs.each do |i| # Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed keys (remember the 520 byte limit on redeemScript size). # That works out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627 # bytes of scriptSig, which we round off to 1650 bytes for some minor future-proofing. # That's also enough to spend a 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not considered standard. return false if i.script_sig.size > 1650 return false unless i.script_sig.push_only? end data_count = 0 outputs.each do |o| return false unless o.script_pubkey.standard? data_count += 1 if o.script_pubkey.op_return? # TODO add non P2SH multisig relay(permitbaremultisig) # TODO add dust relay check end return false if data_count > 1 true end
ruby
def standard? return false if version > MAX_STANDARD_VERSION return false if weight > MAX_STANDARD_TX_WEIGHT inputs.each do |i| # Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed keys (remember the 520 byte limit on redeemScript size). # That works out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627 # bytes of scriptSig, which we round off to 1650 bytes for some minor future-proofing. # That's also enough to spend a 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not considered standard. return false if i.script_sig.size > 1650 return false unless i.script_sig.push_only? end data_count = 0 outputs.each do |o| return false unless o.script_pubkey.standard? data_count += 1 if o.script_pubkey.op_return? # TODO add non P2SH multisig relay(permitbaremultisig) # TODO add dust relay check end return false if data_count > 1 true end
[ "def", "standard?", "return", "false", "if", "version", ">", "MAX_STANDARD_VERSION", "return", "false", "if", "weight", ">", "MAX_STANDARD_TX_WEIGHT", "inputs", ".", "each", "do", "|", "i", "|", "# Biggest 'standard' txin is a 15-of-15 P2SH multisig with compressed keys (remember the 520 byte limit on redeemScript size).", "# That works out to a (15*(33+1))+3=513 byte redeemScript, 513+1+15*(73+1)+3=1627", "# bytes of scriptSig, which we round off to 1650 bytes for some minor future-proofing.", "# That's also enough to spend a 20-of-20 CHECKMULTISIG scriptPubKey, though such a scriptPubKey is not considered standard.", "return", "false", "if", "i", ".", "script_sig", ".", "size", ">", "1650", "return", "false", "unless", "i", ".", "script_sig", ".", "push_only?", "end", "data_count", "=", "0", "outputs", ".", "each", "do", "|", "o", "|", "return", "false", "unless", "o", ".", "script_pubkey", ".", "standard?", "data_count", "+=", "1", "if", "o", ".", "script_pubkey", ".", "op_return?", "# TODO add non P2SH multisig relay(permitbaremultisig)", "# TODO add dust relay check", "end", "return", "false", "if", "data_count", ">", "1", "true", "end" ]
check this tx is standard.
[ "check", "this", "tx", "is", "standard", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L143-L163
18,144
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.sighash_for_input
def sighash_for_input(input_index, output_script, hash_type: SIGHASH_TYPE[:all], sig_version: :base, amount: nil, skip_separator_index: 0) raise ArgumentError, 'input_index must be specified.' unless input_index raise ArgumentError, 'does not exist input corresponding to input_index.' if input_index >= inputs.size raise ArgumentError, 'script_pubkey must be specified.' unless output_script raise ArgumentError, 'unsupported sig version specified.' unless SIG_VERSION.include?(sig_version) if sig_version == :witness_v0 || Bitcoin.chain_params.fork_chain? raise ArgumentError, 'amount must be specified.' unless amount sighash_for_witness(input_index, output_script, hash_type, amount, skip_separator_index) else sighash_for_legacy(input_index, output_script, hash_type) end end
ruby
def sighash_for_input(input_index, output_script, hash_type: SIGHASH_TYPE[:all], sig_version: :base, amount: nil, skip_separator_index: 0) raise ArgumentError, 'input_index must be specified.' unless input_index raise ArgumentError, 'does not exist input corresponding to input_index.' if input_index >= inputs.size raise ArgumentError, 'script_pubkey must be specified.' unless output_script raise ArgumentError, 'unsupported sig version specified.' unless SIG_VERSION.include?(sig_version) if sig_version == :witness_v0 || Bitcoin.chain_params.fork_chain? raise ArgumentError, 'amount must be specified.' unless amount sighash_for_witness(input_index, output_script, hash_type, amount, skip_separator_index) else sighash_for_legacy(input_index, output_script, hash_type) end end
[ "def", "sighash_for_input", "(", "input_index", ",", "output_script", ",", "hash_type", ":", "SIGHASH_TYPE", "[", ":all", "]", ",", "sig_version", ":", ":base", ",", "amount", ":", "nil", ",", "skip_separator_index", ":", "0", ")", "raise", "ArgumentError", ",", "'input_index must be specified.'", "unless", "input_index", "raise", "ArgumentError", ",", "'does not exist input corresponding to input_index.'", "if", "input_index", ">=", "inputs", ".", "size", "raise", "ArgumentError", ",", "'script_pubkey must be specified.'", "unless", "output_script", "raise", "ArgumentError", ",", "'unsupported sig version specified.'", "unless", "SIG_VERSION", ".", "include?", "(", "sig_version", ")", "if", "sig_version", "==", ":witness_v0", "||", "Bitcoin", ".", "chain_params", ".", "fork_chain?", "raise", "ArgumentError", ",", "'amount must be specified.'", "unless", "amount", "sighash_for_witness", "(", "input_index", ",", "output_script", ",", "hash_type", ",", "amount", ",", "skip_separator_index", ")", "else", "sighash_for_legacy", "(", "input_index", ",", "output_script", ",", "hash_type", ")", "end", "end" ]
get signature hash @param [Integer] input_index input index. @param [Integer] hash_type signature hash type @param [Bitcoin::Script] output_script script pubkey or script code. if script pubkey is P2WSH, set witness script to this. @param [Integer] amount bitcoin amount locked in input. required for witness input only. @param [Integer] skip_separator_index If output_script is P2WSH and output_script contains any OP_CODESEPARATOR, the script code needs is the witnessScript but removing everything up to and including the last executed OP_CODESEPARATOR before the signature checking opcode being executed.
[ "get", "signature", "hash" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L192-L205
18,145
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.verify_input_sig
def verify_input_sig(input_index, script_pubkey, amount: nil, flags: STANDARD_SCRIPT_VERIFY_FLAGS) script_sig = inputs[input_index].script_sig has_witness = inputs[input_index].has_witness? if script_pubkey.p2sh? flags << SCRIPT_VERIFY_P2SH redeem_script = Script.parse_from_payload(script_sig.chunks.last) script_pubkey = redeem_script if redeem_script.p2wpkh? end if has_witness || Bitcoin.chain_params.fork_chain? verify_input_sig_for_witness(input_index, script_pubkey, amount, flags) else verify_input_sig_for_legacy(input_index, script_pubkey, flags) end end
ruby
def verify_input_sig(input_index, script_pubkey, amount: nil, flags: STANDARD_SCRIPT_VERIFY_FLAGS) script_sig = inputs[input_index].script_sig has_witness = inputs[input_index].has_witness? if script_pubkey.p2sh? flags << SCRIPT_VERIFY_P2SH redeem_script = Script.parse_from_payload(script_sig.chunks.last) script_pubkey = redeem_script if redeem_script.p2wpkh? end if has_witness || Bitcoin.chain_params.fork_chain? verify_input_sig_for_witness(input_index, script_pubkey, amount, flags) else verify_input_sig_for_legacy(input_index, script_pubkey, flags) end end
[ "def", "verify_input_sig", "(", "input_index", ",", "script_pubkey", ",", "amount", ":", "nil", ",", "flags", ":", "STANDARD_SCRIPT_VERIFY_FLAGS", ")", "script_sig", "=", "inputs", "[", "input_index", "]", ".", "script_sig", "has_witness", "=", "inputs", "[", "input_index", "]", ".", "has_witness?", "if", "script_pubkey", ".", "p2sh?", "flags", "<<", "SCRIPT_VERIFY_P2SH", "redeem_script", "=", "Script", ".", "parse_from_payload", "(", "script_sig", ".", "chunks", ".", "last", ")", "script_pubkey", "=", "redeem_script", "if", "redeem_script", ".", "p2wpkh?", "end", "if", "has_witness", "||", "Bitcoin", ".", "chain_params", ".", "fork_chain?", "verify_input_sig_for_witness", "(", "input_index", ",", "script_pubkey", ",", "amount", ",", "flags", ")", "else", "verify_input_sig_for_legacy", "(", "input_index", ",", "script_pubkey", ",", "flags", ")", "end", "end" ]
verify input signature. @param [Integer] input_index @param [Bitcoin::Script] script_pubkey the script pubkey for target input. @param [Integer] amount the amount of bitcoin, require for witness program only. @param [Array] flags the flags used when execute script interpreter.
[ "verify", "input", "signature", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L212-L227
18,146
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.sighash_for_legacy
def sighash_for_legacy(index, script_code, hash_type) ins = inputs.map.with_index do |i, idx| if idx == index i.to_payload(script_code.delete_opcode(Bitcoin::Opcodes::OP_CODESEPARATOR)) else case hash_type & 0x1f when SIGHASH_TYPE[:none], SIGHASH_TYPE[:single] i.to_payload(Bitcoin::Script.new, 0) else i.to_payload(Bitcoin::Script.new) end end end outs = outputs.map(&:to_payload) out_size = Bitcoin.pack_var_int(outputs.size) case hash_type & 0x1f when SIGHASH_TYPE[:none] outs = '' out_size = Bitcoin.pack_var_int(0) when SIGHASH_TYPE[:single] return "\x01".ljust(32, "\x00") if index >= outputs.size outs = outputs[0...(index + 1)].map.with_index { |o, idx| (idx == index) ? o.to_payload : o.to_empty_payload }.join out_size = Bitcoin.pack_var_int(index + 1) end if hash_type & SIGHASH_TYPE[:anyonecanpay] != 0 ins = [ins[index]] end buf = [[version].pack('V'), Bitcoin.pack_var_int(ins.size), ins, out_size, outs, [lock_time, hash_type].pack('VV')].join Bitcoin.double_sha256(buf) end
ruby
def sighash_for_legacy(index, script_code, hash_type) ins = inputs.map.with_index do |i, idx| if idx == index i.to_payload(script_code.delete_opcode(Bitcoin::Opcodes::OP_CODESEPARATOR)) else case hash_type & 0x1f when SIGHASH_TYPE[:none], SIGHASH_TYPE[:single] i.to_payload(Bitcoin::Script.new, 0) else i.to_payload(Bitcoin::Script.new) end end end outs = outputs.map(&:to_payload) out_size = Bitcoin.pack_var_int(outputs.size) case hash_type & 0x1f when SIGHASH_TYPE[:none] outs = '' out_size = Bitcoin.pack_var_int(0) when SIGHASH_TYPE[:single] return "\x01".ljust(32, "\x00") if index >= outputs.size outs = outputs[0...(index + 1)].map.with_index { |o, idx| (idx == index) ? o.to_payload : o.to_empty_payload }.join out_size = Bitcoin.pack_var_int(index + 1) end if hash_type & SIGHASH_TYPE[:anyonecanpay] != 0 ins = [ins[index]] end buf = [[version].pack('V'), Bitcoin.pack_var_int(ins.size), ins, out_size, outs, [lock_time, hash_type].pack('VV')].join Bitcoin.double_sha256(buf) end
[ "def", "sighash_for_legacy", "(", "index", ",", "script_code", ",", "hash_type", ")", "ins", "=", "inputs", ".", "map", ".", "with_index", "do", "|", "i", ",", "idx", "|", "if", "idx", "==", "index", "i", ".", "to_payload", "(", "script_code", ".", "delete_opcode", "(", "Bitcoin", "::", "Opcodes", "::", "OP_CODESEPARATOR", ")", ")", "else", "case", "hash_type", "&", "0x1f", "when", "SIGHASH_TYPE", "[", ":none", "]", ",", "SIGHASH_TYPE", "[", ":single", "]", "i", ".", "to_payload", "(", "Bitcoin", "::", "Script", ".", "new", ",", "0", ")", "else", "i", ".", "to_payload", "(", "Bitcoin", "::", "Script", ".", "new", ")", "end", "end", "end", "outs", "=", "outputs", ".", "map", "(", ":to_payload", ")", "out_size", "=", "Bitcoin", ".", "pack_var_int", "(", "outputs", ".", "size", ")", "case", "hash_type", "&", "0x1f", "when", "SIGHASH_TYPE", "[", ":none", "]", "outs", "=", "''", "out_size", "=", "Bitcoin", ".", "pack_var_int", "(", "0", ")", "when", "SIGHASH_TYPE", "[", ":single", "]", "return", "\"\\x01\"", ".", "ljust", "(", "32", ",", "\"\\x00\"", ")", "if", "index", ">=", "outputs", ".", "size", "outs", "=", "outputs", "[", "0", "...", "(", "index", "+", "1", ")", "]", ".", "map", ".", "with_index", "{", "|", "o", ",", "idx", "|", "(", "idx", "==", "index", ")", "?", "o", ".", "to_payload", ":", "o", ".", "to_empty_payload", "}", ".", "join", "out_size", "=", "Bitcoin", ".", "pack_var_int", "(", "index", "+", "1", ")", "end", "if", "hash_type", "&", "SIGHASH_TYPE", "[", ":anyonecanpay", "]", "!=", "0", "ins", "=", "[", "ins", "[", "index", "]", "]", "end", "buf", "=", "[", "[", "version", "]", ".", "pack", "(", "'V'", ")", ",", "Bitcoin", ".", "pack_var_int", "(", "ins", ".", "size", ")", ",", "ins", ",", "out_size", ",", "outs", ",", "[", "lock_time", ",", "hash_type", "]", ".", "pack", "(", "'VV'", ")", "]", ".", "join", "Bitcoin", ".", "double_sha256", "(", "buf", ")", "end" ]
generate sighash with legacy format
[ "generate", "sighash", "with", "legacy", "format" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L239-L274
18,147
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.verify_input_sig_for_legacy
def verify_input_sig_for_legacy(input_index, script_pubkey, flags) script_sig = inputs[input_index].script_sig checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index) interpreter = Bitcoin::ScriptInterpreter.new(checker: checker, flags: flags) interpreter.verify_script(script_sig, script_pubkey) end
ruby
def verify_input_sig_for_legacy(input_index, script_pubkey, flags) script_sig = inputs[input_index].script_sig checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index) interpreter = Bitcoin::ScriptInterpreter.new(checker: checker, flags: flags) interpreter.verify_script(script_sig, script_pubkey) end
[ "def", "verify_input_sig_for_legacy", "(", "input_index", ",", "script_pubkey", ",", "flags", ")", "script_sig", "=", "inputs", "[", "input_index", "]", ".", "script_sig", "checker", "=", "Bitcoin", "::", "TxChecker", ".", "new", "(", "tx", ":", "self", ",", "input_index", ":", "input_index", ")", "interpreter", "=", "Bitcoin", "::", "ScriptInterpreter", ".", "new", "(", "checker", ":", "checker", ",", "flags", ":", "flags", ")", "interpreter", ".", "verify_script", "(", "script_sig", ",", "script_pubkey", ")", "end" ]
verify input signature for legacy tx.
[ "verify", "input", "signature", "for", "legacy", "tx", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L306-L312
18,148
chaintope/bitcoinrb
lib/bitcoin/tx.rb
Bitcoin.Tx.verify_input_sig_for_witness
def verify_input_sig_for_witness(input_index, script_pubkey, amount, flags) flags |= SCRIPT_VERIFY_WITNESS flags |= SCRIPT_VERIFY_WITNESS_PUBKEYTYPE checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index, amount: amount) interpreter = Bitcoin::ScriptInterpreter.new(checker: checker, flags: flags) i = inputs[input_index] script_sig = i.script_sig witness = i.script_witness interpreter.verify_script(script_sig, script_pubkey, witness) end
ruby
def verify_input_sig_for_witness(input_index, script_pubkey, amount, flags) flags |= SCRIPT_VERIFY_WITNESS flags |= SCRIPT_VERIFY_WITNESS_PUBKEYTYPE checker = Bitcoin::TxChecker.new(tx: self, input_index: input_index, amount: amount) interpreter = Bitcoin::ScriptInterpreter.new(checker: checker, flags: flags) i = inputs[input_index] script_sig = i.script_sig witness = i.script_witness interpreter.verify_script(script_sig, script_pubkey, witness) end
[ "def", "verify_input_sig_for_witness", "(", "input_index", ",", "script_pubkey", ",", "amount", ",", "flags", ")", "flags", "|=", "SCRIPT_VERIFY_WITNESS", "flags", "|=", "SCRIPT_VERIFY_WITNESS_PUBKEYTYPE", "checker", "=", "Bitcoin", "::", "TxChecker", ".", "new", "(", "tx", ":", "self", ",", "input_index", ":", "input_index", ",", "amount", ":", "amount", ")", "interpreter", "=", "Bitcoin", "::", "ScriptInterpreter", ".", "new", "(", "checker", ":", "checker", ",", "flags", ":", "flags", ")", "i", "=", "inputs", "[", "input_index", "]", "script_sig", "=", "i", ".", "script_sig", "witness", "=", "i", ".", "script_witness", "interpreter", ".", "verify_script", "(", "script_sig", ",", "script_pubkey", ",", "witness", ")", "end" ]
verify input signature for witness tx.
[ "verify", "input", "signature", "for", "witness", "tx", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/tx.rb#L315-L325
18,149
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtKey.ext_pubkey
def ext_pubkey k = ExtPubkey.new k.depth = depth k.number = number k.parent_fingerprint = parent_fingerprint k.chain_code = chain_code k.pubkey = key.pubkey k.ver = priv_ver_to_pub_ver k end
ruby
def ext_pubkey k = ExtPubkey.new k.depth = depth k.number = number k.parent_fingerprint = parent_fingerprint k.chain_code = chain_code k.pubkey = key.pubkey k.ver = priv_ver_to_pub_ver k end
[ "def", "ext_pubkey", "k", "=", "ExtPubkey", ".", "new", "k", ".", "depth", "=", "depth", "k", ".", "number", "=", "number", "k", ".", "parent_fingerprint", "=", "parent_fingerprint", "k", ".", "chain_code", "=", "chain_code", "k", ".", "pubkey", "=", "key", ".", "pubkey", "k", ".", "ver", "=", "priv_ver_to_pub_ver", "k", "end" ]
get ExtPubkey from priv_key
[ "get", "ExtPubkey", "from", "priv_key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L33-L42
18,150
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtKey.to_payload
def to_payload version.htb << [depth].pack('C') << parent_fingerprint.htb << [number].pack('N') << chain_code << [0x00].pack('C') << key.priv_key.htb end
ruby
def to_payload version.htb << [depth].pack('C') << parent_fingerprint.htb << [number].pack('N') << chain_code << [0x00].pack('C') << key.priv_key.htb end
[ "def", "to_payload", "version", ".", "htb", "<<", "[", "depth", "]", ".", "pack", "(", "'C'", ")", "<<", "parent_fingerprint", ".", "htb", "<<", "[", "number", "]", ".", "pack", "(", "'N'", ")", "<<", "chain_code", "<<", "[", "0x00", "]", ".", "pack", "(", "'C'", ")", "<<", "key", ".", "priv_key", ".", "htb", "end" ]
serialize extended private key
[ "serialize", "extended", "private", "key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L45-L48
18,151
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtKey.to_base58
def to_base58 h = to_payload.bth hex = h + Bitcoin.calc_checksum(h) Base58.encode(hex) end
ruby
def to_base58 h = to_payload.bth hex = h + Bitcoin.calc_checksum(h) Base58.encode(hex) end
[ "def", "to_base58", "h", "=", "to_payload", ".", "bth", "hex", "=", "h", "+", "Bitcoin", ".", "calc_checksum", "(", "h", ")", "Base58", ".", "encode", "(", "hex", ")", "end" ]
Base58 encoded extended private key
[ "Base58", "encoded", "extended", "private", "key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L51-L55
18,152
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtKey.derive
def derive(number, harden = false) number += HARDENED_THRESHOLD if harden new_key = ExtKey.new new_key.depth = depth + 1 new_key.number = number new_key.parent_fingerprint = fingerprint if number > (HARDENED_THRESHOLD - 1) data = [0x00].pack('C') << key.priv_key.htb << [number].pack('N') else data = key.pubkey.htb << [number].pack('N') end l = Bitcoin.hmac_sha512(chain_code, data) left = l[0..31].bth.to_i(16) raise 'invalid key' if left >= CURVE_ORDER child_priv = (left + key.priv_key.to_i(16)) % CURVE_ORDER raise 'invalid key ' if child_priv >= CURVE_ORDER new_key.key = Bitcoin::Key.new( priv_key: child_priv.to_even_length_hex.rjust(64, '0'), key_type: key_type) new_key.chain_code = l[32..-1] new_key.ver = version new_key end
ruby
def derive(number, harden = false) number += HARDENED_THRESHOLD if harden new_key = ExtKey.new new_key.depth = depth + 1 new_key.number = number new_key.parent_fingerprint = fingerprint if number > (HARDENED_THRESHOLD - 1) data = [0x00].pack('C') << key.priv_key.htb << [number].pack('N') else data = key.pubkey.htb << [number].pack('N') end l = Bitcoin.hmac_sha512(chain_code, data) left = l[0..31].bth.to_i(16) raise 'invalid key' if left >= CURVE_ORDER child_priv = (left + key.priv_key.to_i(16)) % CURVE_ORDER raise 'invalid key ' if child_priv >= CURVE_ORDER new_key.key = Bitcoin::Key.new( priv_key: child_priv.to_even_length_hex.rjust(64, '0'), key_type: key_type) new_key.chain_code = l[32..-1] new_key.ver = version new_key end
[ "def", "derive", "(", "number", ",", "harden", "=", "false", ")", "number", "+=", "HARDENED_THRESHOLD", "if", "harden", "new_key", "=", "ExtKey", ".", "new", "new_key", ".", "depth", "=", "depth", "+", "1", "new_key", ".", "number", "=", "number", "new_key", ".", "parent_fingerprint", "=", "fingerprint", "if", "number", ">", "(", "HARDENED_THRESHOLD", "-", "1", ")", "data", "=", "[", "0x00", "]", ".", "pack", "(", "'C'", ")", "<<", "key", ".", "priv_key", ".", "htb", "<<", "[", "number", "]", ".", "pack", "(", "'N'", ")", "else", "data", "=", "key", ".", "pubkey", ".", "htb", "<<", "[", "number", "]", ".", "pack", "(", "'N'", ")", "end", "l", "=", "Bitcoin", ".", "hmac_sha512", "(", "chain_code", ",", "data", ")", "left", "=", "l", "[", "0", "..", "31", "]", ".", "bth", ".", "to_i", "(", "16", ")", "raise", "'invalid key'", "if", "left", ">=", "CURVE_ORDER", "child_priv", "=", "(", "left", "+", "key", ".", "priv_key", ".", "to_i", "(", "16", ")", ")", "%", "CURVE_ORDER", "raise", "'invalid key '", "if", "child_priv", ">=", "CURVE_ORDER", "new_key", ".", "key", "=", "Bitcoin", "::", "Key", ".", "new", "(", "priv_key", ":", "child_priv", ".", "to_even_length_hex", ".", "rjust", "(", "64", ",", "'0'", ")", ",", "key_type", ":", "key_type", ")", "new_key", ".", "chain_code", "=", "l", "[", "32", "..", "-", "1", "]", "new_key", ".", "ver", "=", "version", "new_key", "end" ]
derive new key @param [Integer] number a child index @param [Boolean] harden whether hardened key or not. If true, 2^31 is added to +number+. @return [Bitcoin::ExtKey] derived new key.
[ "derive", "new", "key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L95-L116
18,153
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtKey.priv_ver_to_pub_ver
def priv_ver_to_pub_ver case version when Bitcoin.chain_params.bip49_privkey_p2wpkh_p2sh_version Bitcoin.chain_params.bip49_pubkey_p2wpkh_p2sh_version when Bitcoin.chain_params.bip84_privkey_p2wpkh_version Bitcoin.chain_params.bip84_pubkey_p2wpkh_version else Bitcoin.chain_params.extended_pubkey_version end end
ruby
def priv_ver_to_pub_ver case version when Bitcoin.chain_params.bip49_privkey_p2wpkh_p2sh_version Bitcoin.chain_params.bip49_pubkey_p2wpkh_p2sh_version when Bitcoin.chain_params.bip84_privkey_p2wpkh_version Bitcoin.chain_params.bip84_pubkey_p2wpkh_version else Bitcoin.chain_params.extended_pubkey_version end end
[ "def", "priv_ver_to_pub_ver", "case", "version", "when", "Bitcoin", ".", "chain_params", ".", "bip49_privkey_p2wpkh_p2sh_version", "Bitcoin", ".", "chain_params", ".", "bip49_pubkey_p2wpkh_p2sh_version", "when", "Bitcoin", ".", "chain_params", ".", "bip84_privkey_p2wpkh_version", "Bitcoin", ".", "chain_params", ".", "bip84_pubkey_p2wpkh_version", "else", "Bitcoin", ".", "chain_params", ".", "extended_pubkey_version", "end", "end" ]
convert privkey version to pubkey version
[ "convert", "privkey", "version", "to", "pubkey", "version" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L176-L185
18,154
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtPubkey.to_payload
def to_payload version.htb << [depth].pack('C') << parent_fingerprint.htb << [number].pack('N') << chain_code << pub.htb end
ruby
def to_payload version.htb << [depth].pack('C') << parent_fingerprint.htb << [number].pack('N') << chain_code << pub.htb end
[ "def", "to_payload", "version", ".", "htb", "<<", "[", "depth", "]", ".", "pack", "(", "'C'", ")", "<<", "parent_fingerprint", ".", "htb", "<<", "[", "number", "]", ".", "pack", "(", "'N'", ")", "<<", "chain_code", "<<", "pub", ".", "htb", "end" ]
serialize extended pubkey
[ "serialize", "extended", "pubkey" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L200-L203
18,155
chaintope/bitcoinrb
lib/bitcoin/ext_key.rb
Bitcoin.ExtPubkey.derive
def derive(number) new_key = ExtPubkey.new new_key.depth = depth + 1 new_key.number = number new_key.parent_fingerprint = fingerprint raise 'hardened key is not support' if number > (HARDENED_THRESHOLD - 1) data = pub.htb << [number].pack('N') l = Bitcoin.hmac_sha512(chain_code, data) left = l[0..31].bth.to_i(16) raise 'invalid key' if left >= CURVE_ORDER p1 = Bitcoin::Secp256k1::GROUP.generator.multiply_by_scalar(left) p2 = Bitcoin::Key.new(pubkey: pubkey, key_type: key_type).to_point new_key.pubkey = ECDSA::Format::PointOctetString.encode(p1 + p2, compression: true).bth new_key.chain_code = l[32..-1] new_key.ver = version new_key end
ruby
def derive(number) new_key = ExtPubkey.new new_key.depth = depth + 1 new_key.number = number new_key.parent_fingerprint = fingerprint raise 'hardened key is not support' if number > (HARDENED_THRESHOLD - 1) data = pub.htb << [number].pack('N') l = Bitcoin.hmac_sha512(chain_code, data) left = l[0..31].bth.to_i(16) raise 'invalid key' if left >= CURVE_ORDER p1 = Bitcoin::Secp256k1::GROUP.generator.multiply_by_scalar(left) p2 = Bitcoin::Key.new(pubkey: pubkey, key_type: key_type).to_point new_key.pubkey = ECDSA::Format::PointOctetString.encode(p1 + p2, compression: true).bth new_key.chain_code = l[32..-1] new_key.ver = version new_key end
[ "def", "derive", "(", "number", ")", "new_key", "=", "ExtPubkey", ".", "new", "new_key", ".", "depth", "=", "depth", "+", "1", "new_key", ".", "number", "=", "number", "new_key", ".", "parent_fingerprint", "=", "fingerprint", "raise", "'hardened key is not support'", "if", "number", ">", "(", "HARDENED_THRESHOLD", "-", "1", ")", "data", "=", "pub", ".", "htb", "<<", "[", "number", "]", ".", "pack", "(", "'N'", ")", "l", "=", "Bitcoin", ".", "hmac_sha512", "(", "chain_code", ",", "data", ")", "left", "=", "l", "[", "0", "..", "31", "]", ".", "bth", ".", "to_i", "(", "16", ")", "raise", "'invalid key'", "if", "left", ">=", "CURVE_ORDER", "p1", "=", "Bitcoin", "::", "Secp256k1", "::", "GROUP", ".", "generator", ".", "multiply_by_scalar", "(", "left", ")", "p2", "=", "Bitcoin", "::", "Key", ".", "new", "(", "pubkey", ":", "pubkey", ",", "key_type", ":", "key_type", ")", ".", "to_point", "new_key", ".", "pubkey", "=", "ECDSA", "::", "Format", "::", "PointOctetString", ".", "encode", "(", "p1", "+", "p2", ",", "compression", ":", "true", ")", ".", "bth", "new_key", ".", "chain_code", "=", "l", "[", "32", "..", "-", "1", "]", "new_key", ".", "ver", "=", "version", "new_key", "end" ]
derive child key
[ "derive", "child", "key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/ext_key.rb#L254-L270
18,156
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.p2pkh?
def p2pkh? return false unless chunks.size == 5 [OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG] == (chunks[0..1]+ chunks[3..4]).map(&:ord) && chunks[2].bytesize == 21 end
ruby
def p2pkh? return false unless chunks.size == 5 [OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG] == (chunks[0..1]+ chunks[3..4]).map(&:ord) && chunks[2].bytesize == 21 end
[ "def", "p2pkh?", "return", "false", "unless", "chunks", ".", "size", "==", "5", "[", "OP_DUP", ",", "OP_HASH160", ",", "OP_EQUALVERIFY", ",", "OP_CHECKSIG", "]", "==", "(", "chunks", "[", "0", "..", "1", "]", "+", "chunks", "[", "3", "..", "4", "]", ")", ".", "map", "(", ":ord", ")", "&&", "chunks", "[", "2", "]", ".", "bytesize", "==", "21", "end" ]
whether this script is a P2PKH format script.
[ "whether", "this", "script", "is", "a", "P2PKH", "format", "script", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L169-L173
18,157
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.push_only?
def push_only? chunks.each do |c| return false if !c.opcode.nil? && c.opcode > OP_16 end true end
ruby
def push_only? chunks.each do |c| return false if !c.opcode.nil? && c.opcode > OP_16 end true end
[ "def", "push_only?", "chunks", ".", "each", "do", "|", "c", "|", "return", "false", "if", "!", "c", ".", "opcode", ".", "nil?", "&&", "c", ".", "opcode", ">", "OP_16", "end", "true", "end" ]
whether data push only script which dose not include other opcode
[ "whether", "data", "push", "only", "script", "which", "dose", "not", "include", "other", "opcode" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L215-L220
18,158
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.witness_program?
def witness_program? return false if size < 4 || size > 42 || chunks.size < 2 opcode = chunks[0].opcode return false if opcode != OP_0 && (opcode < OP_1 || opcode > OP_16) return false unless chunks[1].pushdata? if size == (chunks[1][0].unpack('C').first + 2) program_size = chunks[1].pushed_data.bytesize return program_size >= 2 && program_size <= 40 end false end
ruby
def witness_program? return false if size < 4 || size > 42 || chunks.size < 2 opcode = chunks[0].opcode return false if opcode != OP_0 && (opcode < OP_1 || opcode > OP_16) return false unless chunks[1].pushdata? if size == (chunks[1][0].unpack('C').first + 2) program_size = chunks[1].pushed_data.bytesize return program_size >= 2 && program_size <= 40 end false end
[ "def", "witness_program?", "return", "false", "if", "size", "<", "4", "||", "size", ">", "42", "||", "chunks", ".", "size", "<", "2", "opcode", "=", "chunks", "[", "0", "]", ".", "opcode", "return", "false", "if", "opcode", "!=", "OP_0", "&&", "(", "opcode", "<", "OP_1", "||", "opcode", ">", "OP_16", ")", "return", "false", "unless", "chunks", "[", "1", "]", ".", "pushdata?", "if", "size", "==", "(", "chunks", "[", "1", "]", "[", "0", "]", ".", "unpack", "(", "'C'", ")", ".", "first", "+", "2", ")", "program_size", "=", "chunks", "[", "1", "]", ".", "pushed_data", ".", "bytesize", "return", "program_size", ">=", "2", "&&", "program_size", "<=", "40", "end", "false", "end" ]
A witness program is any valid Script that consists of a 1-byte push opcode followed by a data push between 2 and 40 bytes.
[ "A", "witness", "program", "is", "any", "valid", "Script", "that", "consists", "of", "a", "1", "-", "byte", "push", "opcode", "followed", "by", "a", "data", "push", "between", "2", "and", "40", "bytes", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L223-L237
18,159
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.witness_commitment
def witness_commitment return nil if !op_return? || op_return_data.bytesize < 36 buf = StringIO.new(op_return_data) return nil unless buf.read(4).bth == WITNESS_COMMITMENT_HEADER buf.read(32).bth end
ruby
def witness_commitment return nil if !op_return? || op_return_data.bytesize < 36 buf = StringIO.new(op_return_data) return nil unless buf.read(4).bth == WITNESS_COMMITMENT_HEADER buf.read(32).bth end
[ "def", "witness_commitment", "return", "nil", "if", "!", "op_return?", "||", "op_return_data", ".", "bytesize", "<", "36", "buf", "=", "StringIO", ".", "new", "(", "op_return_data", ")", "return", "nil", "unless", "buf", ".", "read", "(", "4", ")", ".", "bth", "==", "WITNESS_COMMITMENT_HEADER", "buf", ".", "read", "(", "32", ")", ".", "bth", "end" ]
get witness commitment
[ "get", "witness", "commitment" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L240-L245
18,160
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.to_script_code
def to_script_code(skip_separator_index = 0) payload = to_payload if p2wpkh? payload = Script.to_p2pkh(chunks[1].pushed_data.bth).to_payload elsif skip_separator_index > 0 payload = subscript_codeseparator(skip_separator_index) end Bitcoin.pack_var_string(payload) end
ruby
def to_script_code(skip_separator_index = 0) payload = to_payload if p2wpkh? payload = Script.to_p2pkh(chunks[1].pushed_data.bth).to_payload elsif skip_separator_index > 0 payload = subscript_codeseparator(skip_separator_index) end Bitcoin.pack_var_string(payload) end
[ "def", "to_script_code", "(", "skip_separator_index", "=", "0", ")", "payload", "=", "to_payload", "if", "p2wpkh?", "payload", "=", "Script", ".", "to_p2pkh", "(", "chunks", "[", "1", "]", ".", "pushed_data", ".", "bth", ")", ".", "to_payload", "elsif", "skip_separator_index", ">", "0", "payload", "=", "subscript_codeseparator", "(", "skip_separator_index", ")", "end", "Bitcoin", ".", "pack_var_string", "(", "payload", ")", "end" ]
If this script is witness program, return its script code, otherwise returns the self payload. ScriptInterpreter does not use this.
[ "If", "this", "script", "is", "witness", "program", "return", "its", "script", "code", "otherwise", "returns", "the", "self", "payload", ".", "ScriptInterpreter", "does", "not", "use", "this", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L249-L257
18,161
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.witness_data
def witness_data version = opcode_to_small_int(chunks[0].opcode) program = chunks[1].pushed_data [version, program] end
ruby
def witness_data version = opcode_to_small_int(chunks[0].opcode) program = chunks[1].pushed_data [version, program] end
[ "def", "witness_data", "version", "=", "opcode_to_small_int", "(", "chunks", "[", "0", "]", ".", "opcode", ")", "program", "=", "chunks", "[", "1", "]", ".", "pushed_data", "[", "version", ",", "program", "]", "end" ]
get witness version and witness program
[ "get", "witness", "version", "and", "witness", "program" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L260-L264
18,162
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.<<
def <<(obj) if obj.is_a?(Integer) push_int(obj) elsif obj.is_a?(String) append_data(obj) elsif obj.is_a?(Array) obj.each { |o| self.<< o} self end end
ruby
def <<(obj) if obj.is_a?(Integer) push_int(obj) elsif obj.is_a?(String) append_data(obj) elsif obj.is_a?(Array) obj.each { |o| self.<< o} self end end
[ "def", "<<", "(", "obj", ")", "if", "obj", ".", "is_a?", "(", "Integer", ")", "push_int", "(", "obj", ")", "elsif", "obj", ".", "is_a?", "(", "String", ")", "append_data", "(", "obj", ")", "elsif", "obj", ".", "is_a?", "(", "Array", ")", "obj", ".", "each", "{", "|", "o", "|", "self", ".", "<<", "o", "}", "self", "end", "end" ]
append object to payload
[ "append", "object", "to", "payload" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L267-L276
18,163
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.append_opcode
def append_opcode(opcode) opcode = Opcodes.small_int_to_opcode(opcode) if -1 <= opcode && opcode <= 16 raise ArgumentError, "specified invalid opcode #{opcode}." unless Opcodes.defined?(opcode) chunks << opcode.chr self end
ruby
def append_opcode(opcode) opcode = Opcodes.small_int_to_opcode(opcode) if -1 <= opcode && opcode <= 16 raise ArgumentError, "specified invalid opcode #{opcode}." unless Opcodes.defined?(opcode) chunks << opcode.chr self end
[ "def", "append_opcode", "(", "opcode", ")", "opcode", "=", "Opcodes", ".", "small_int_to_opcode", "(", "opcode", ")", "if", "-", "1", "<=", "opcode", "&&", "opcode", "<=", "16", "raise", "ArgumentError", ",", "\"specified invalid opcode #{opcode}.\"", "unless", "Opcodes", ".", "defined?", "(", "opcode", ")", "chunks", "<<", "opcode", ".", "chr", "self", "end" ]
append opcode to payload @param [Integer] opcode append opcode which defined by Bitcoin::Opcodes @return [Script] return self
[ "append", "opcode", "to", "payload" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L291-L296
18,164
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.append_data
def append_data(data) data = Encoding::ASCII_8BIT == data.encoding ? data : data.htb chunks << Bitcoin::Script.pack_pushdata(data) self end
ruby
def append_data(data) data = Encoding::ASCII_8BIT == data.encoding ? data : data.htb chunks << Bitcoin::Script.pack_pushdata(data) self end
[ "def", "append_data", "(", "data", ")", "data", "=", "Encoding", "::", "ASCII_8BIT", "==", "data", ".", "encoding", "?", "data", ":", "data", ".", "htb", "chunks", "<<", "Bitcoin", "::", "Script", ".", "pack_pushdata", "(", "data", ")", "self", "end" ]
append data to payload with pushdata opcode @param [String] data append data. this data is not binary @return [Script] return self
[ "append", "data", "to", "payload", "with", "pushdata", "opcode" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L301-L305
18,165
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.include?
def include?(item) chunk_item = if item.is_a?(Integer) item.chr elsif item.is_a?(String) data = Encoding::ASCII_8BIT == item.encoding ? item : item.htb Bitcoin::Script.pack_pushdata(data) end return false unless chunk_item chunks.include?(chunk_item) end
ruby
def include?(item) chunk_item = if item.is_a?(Integer) item.chr elsif item.is_a?(String) data = Encoding::ASCII_8BIT == item.encoding ? item : item.htb Bitcoin::Script.pack_pushdata(data) end return false unless chunk_item chunks.include?(chunk_item) end
[ "def", "include?", "(", "item", ")", "chunk_item", "=", "if", "item", ".", "is_a?", "(", "Integer", ")", "item", ".", "chr", "elsif", "item", ".", "is_a?", "(", "String", ")", "data", "=", "Encoding", "::", "ASCII_8BIT", "==", "item", ".", "encoding", "?", "item", ":", "item", ".", "htb", "Bitcoin", "::", "Script", ".", "pack_pushdata", "(", "data", ")", "end", "return", "false", "unless", "chunk_item", "chunks", ".", "include?", "(", "chunk_item", ")", "end" ]
Check the item is in the chunk of the script.
[ "Check", "the", "item", "is", "in", "the", "chunk", "of", "the", "script", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L308-L317
18,166
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.find_and_delete
def find_and_delete(subscript) raise ArgumentError, 'subscript must be Bitcoin::Script' unless subscript.is_a?(Script) return self if subscript.chunks.empty? buf = [] i = 0 result = Script.new chunks.each do |chunk| sub_chunk = subscript.chunks[i] if chunk.start_with?(sub_chunk) if chunk == sub_chunk buf << chunk i += 1 (i = 0; buf.clear) if i == subscript.chunks.size # matched the whole subscript else # matched the part of head i = 0 tmp = chunk.dup tmp.slice!(sub_chunk) result.chunks << tmp end else result.chunks << buf.join unless buf.empty? if buf.first == chunk i = 1 buf = [chunk] else i = 0 result.chunks << chunk end end end result end
ruby
def find_and_delete(subscript) raise ArgumentError, 'subscript must be Bitcoin::Script' unless subscript.is_a?(Script) return self if subscript.chunks.empty? buf = [] i = 0 result = Script.new chunks.each do |chunk| sub_chunk = subscript.chunks[i] if chunk.start_with?(sub_chunk) if chunk == sub_chunk buf << chunk i += 1 (i = 0; buf.clear) if i == subscript.chunks.size # matched the whole subscript else # matched the part of head i = 0 tmp = chunk.dup tmp.slice!(sub_chunk) result.chunks << tmp end else result.chunks << buf.join unless buf.empty? if buf.first == chunk i = 1 buf = [chunk] else i = 0 result.chunks << chunk end end end result end
[ "def", "find_and_delete", "(", "subscript", ")", "raise", "ArgumentError", ",", "'subscript must be Bitcoin::Script'", "unless", "subscript", ".", "is_a?", "(", "Script", ")", "return", "self", "if", "subscript", ".", "chunks", ".", "empty?", "buf", "=", "[", "]", "i", "=", "0", "result", "=", "Script", ".", "new", "chunks", ".", "each", "do", "|", "chunk", "|", "sub_chunk", "=", "subscript", ".", "chunks", "[", "i", "]", "if", "chunk", ".", "start_with?", "(", "sub_chunk", ")", "if", "chunk", "==", "sub_chunk", "buf", "<<", "chunk", "i", "+=", "1", "(", "i", "=", "0", ";", "buf", ".", "clear", ")", "if", "i", "==", "subscript", ".", "chunks", ".", "size", "# matched the whole subscript", "else", "# matched the part of head", "i", "=", "0", "tmp", "=", "chunk", ".", "dup", "tmp", ".", "slice!", "(", "sub_chunk", ")", "result", ".", "chunks", "<<", "tmp", "end", "else", "result", ".", "chunks", "<<", "buf", ".", "join", "unless", "buf", ".", "empty?", "if", "buf", ".", "first", "==", "chunk", "i", "=", "1", "buf", "=", "[", "chunk", "]", "else", "i", "=", "0", "result", ".", "chunks", "<<", "chunk", "end", "end", "end", "result", "end" ]
removes chunks matching subscript byte-for-byte and returns as a new object.
[ "removes", "chunks", "matching", "subscript", "byte", "-", "for", "-", "byte", "and", "returns", "as", "a", "new", "object", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L422-L453
18,167
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.subscript_codeseparator
def subscript_codeseparator(separator_index) buf = [] process_separator_index = 0 chunks.each{|chunk| buf << chunk if process_separator_index == separator_index if chunk.ord == OP_CODESEPARATOR && process_separator_index < separator_index process_separator_index += 1 end } buf.join end
ruby
def subscript_codeseparator(separator_index) buf = [] process_separator_index = 0 chunks.each{|chunk| buf << chunk if process_separator_index == separator_index if chunk.ord == OP_CODESEPARATOR && process_separator_index < separator_index process_separator_index += 1 end } buf.join end
[ "def", "subscript_codeseparator", "(", "separator_index", ")", "buf", "=", "[", "]", "process_separator_index", "=", "0", "chunks", ".", "each", "{", "|", "chunk", "|", "buf", "<<", "chunk", "if", "process_separator_index", "==", "separator_index", "if", "chunk", ".", "ord", "==", "OP_CODESEPARATOR", "&&", "process_separator_index", "<", "separator_index", "process_separator_index", "+=", "1", "end", "}", "buf", ".", "join", "end" ]
Returns a script that deleted the script before the index specified by separator_index.
[ "Returns", "a", "script", "that", "deleted", "the", "script", "before", "the", "index", "specified", "by", "separator_index", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L462-L472
18,168
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.p2pkh_addr
def p2pkh_addr return nil unless p2pkh? hash160 = chunks[2].pushed_data.bth return nil unless hash160.htb.bytesize == 20 Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.address_version) end
ruby
def p2pkh_addr return nil unless p2pkh? hash160 = chunks[2].pushed_data.bth return nil unless hash160.htb.bytesize == 20 Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.address_version) end
[ "def", "p2pkh_addr", "return", "nil", "unless", "p2pkh?", "hash160", "=", "chunks", "[", "2", "]", ".", "pushed_data", ".", "bth", "return", "nil", "unless", "hash160", ".", "htb", ".", "bytesize", "==", "20", "Bitcoin", ".", "encode_base58_address", "(", "hash160", ",", "Bitcoin", ".", "chain_params", ".", "address_version", ")", "end" ]
generate p2pkh address. if script dose not p2pkh, return nil.
[ "generate", "p2pkh", "address", ".", "if", "script", "dose", "not", "p2pkh", "return", "nil", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L501-L506
18,169
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.p2sh_addr
def p2sh_addr return nil unless p2sh? hash160 = chunks[1].pushed_data.bth return nil unless hash160.htb.bytesize == 20 Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.p2sh_version) end
ruby
def p2sh_addr return nil unless p2sh? hash160 = chunks[1].pushed_data.bth return nil unless hash160.htb.bytesize == 20 Bitcoin.encode_base58_address(hash160, Bitcoin.chain_params.p2sh_version) end
[ "def", "p2sh_addr", "return", "nil", "unless", "p2sh?", "hash160", "=", "chunks", "[", "1", "]", ".", "pushed_data", ".", "bth", "return", "nil", "unless", "hash160", ".", "htb", ".", "bytesize", "==", "20", "Bitcoin", ".", "encode_base58_address", "(", "hash160", ",", "Bitcoin", ".", "chain_params", ".", "p2sh_version", ")", "end" ]
generate p2sh address. if script dose not p2sh, return nil.
[ "generate", "p2sh", "address", ".", "if", "script", "dose", "not", "p2sh", "return", "nil", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L514-L519
18,170
chaintope/bitcoinrb
lib/bitcoin/script/script.rb
Bitcoin.Script.bech32_addr
def bech32_addr segwit_addr = Bech32::SegwitAddr.new segwit_addr.hrp = Bitcoin.chain_params.bech32_hrp segwit_addr.script_pubkey = to_payload.bth segwit_addr.addr end
ruby
def bech32_addr segwit_addr = Bech32::SegwitAddr.new segwit_addr.hrp = Bitcoin.chain_params.bech32_hrp segwit_addr.script_pubkey = to_payload.bth segwit_addr.addr end
[ "def", "bech32_addr", "segwit_addr", "=", "Bech32", "::", "SegwitAddr", ".", "new", "segwit_addr", ".", "hrp", "=", "Bitcoin", ".", "chain_params", ".", "bech32_hrp", "segwit_addr", ".", "script_pubkey", "=", "to_payload", ".", "bth", "segwit_addr", ".", "addr", "end" ]
return bech32 address for payload
[ "return", "bech32", "address", "for", "payload" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script.rb#L527-L532
18,171
chaintope/bitcoinrb
lib/bitcoin/mnemonic.rb
Bitcoin.Mnemonic.to_entropy
def to_entropy(words) word_master = load_words mnemonic = words.map do |w| index = word_master.index(w.downcase) raise IndexError, 'word not found in words list.' unless index index.to_s(2).rjust(11, '0') end.join entropy = mnemonic.slice(0, (mnemonic.length * 32) / 33) checksum = mnemonic.gsub(entropy, '') raise SecurityError, 'checksum mismatch.' unless checksum == checksum(entropy) [entropy].pack('B*').bth end
ruby
def to_entropy(words) word_master = load_words mnemonic = words.map do |w| index = word_master.index(w.downcase) raise IndexError, 'word not found in words list.' unless index index.to_s(2).rjust(11, '0') end.join entropy = mnemonic.slice(0, (mnemonic.length * 32) / 33) checksum = mnemonic.gsub(entropy, '') raise SecurityError, 'checksum mismatch.' unless checksum == checksum(entropy) [entropy].pack('B*').bth end
[ "def", "to_entropy", "(", "words", ")", "word_master", "=", "load_words", "mnemonic", "=", "words", ".", "map", "do", "|", "w", "|", "index", "=", "word_master", ".", "index", "(", "w", ".", "downcase", ")", "raise", "IndexError", ",", "'word not found in words list.'", "unless", "index", "index", ".", "to_s", "(", "2", ")", ".", "rjust", "(", "11", ",", "'0'", ")", "end", ".", "join", "entropy", "=", "mnemonic", ".", "slice", "(", "0", ",", "(", "mnemonic", ".", "length", "*", "32", ")", "/", "33", ")", "checksum", "=", "mnemonic", ".", "gsub", "(", "entropy", ",", "''", ")", "raise", "SecurityError", ",", "'checksum mismatch.'", "unless", "checksum", "==", "checksum", "(", "entropy", ")", "[", "entropy", "]", ".", "pack", "(", "'B*'", ")", ".", "bth", "end" ]
generate entropy from mnemonic word @param [Array[String]] words the array of mnemonic word. @return [String] an entropy with hex format.
[ "generate", "entropy", "from", "mnemonic", "word" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/mnemonic.rb#L24-L35
18,172
chaintope/bitcoinrb
lib/bitcoin/mnemonic.rb
Bitcoin.Mnemonic.to_mnemonic
def to_mnemonic(entropy) raise ArgumentError, 'entropy is empty.' if entropy.nil? || entropy.empty? e = entropy.htb.unpack('B*').first seed = e + checksum(e) mnemonic_index = seed.chars.each_slice(11).map{|i|i.join.to_i(2)} word_master = load_words mnemonic_index.map{|i|word_master[i]} end
ruby
def to_mnemonic(entropy) raise ArgumentError, 'entropy is empty.' if entropy.nil? || entropy.empty? e = entropy.htb.unpack('B*').first seed = e + checksum(e) mnemonic_index = seed.chars.each_slice(11).map{|i|i.join.to_i(2)} word_master = load_words mnemonic_index.map{|i|word_master[i]} end
[ "def", "to_mnemonic", "(", "entropy", ")", "raise", "ArgumentError", ",", "'entropy is empty.'", "if", "entropy", ".", "nil?", "||", "entropy", ".", "empty?", "e", "=", "entropy", ".", "htb", ".", "unpack", "(", "'B*'", ")", ".", "first", "seed", "=", "e", "+", "checksum", "(", "e", ")", "mnemonic_index", "=", "seed", ".", "chars", ".", "each_slice", "(", "11", ")", ".", "map", "{", "|", "i", "|", "i", ".", "join", ".", "to_i", "(", "2", ")", "}", "word_master", "=", "load_words", "mnemonic_index", ".", "map", "{", "|", "i", "|", "word_master", "[", "i", "]", "}", "end" ]
generate mnemonic words from entropy. @param [String] entropy an entropy with hex format. @return [Array] the array of mnemonic word.
[ "generate", "mnemonic", "words", "from", "entropy", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/mnemonic.rb#L40-L47
18,173
chaintope/bitcoinrb
lib/bitcoin/mnemonic.rb
Bitcoin.Mnemonic.to_seed
def to_seed(mnemonic, passphrase: '') to_entropy(mnemonic) OpenSSL::PKCS5.pbkdf2_hmac(mnemonic.join(' ').downcase, 'mnemonic' + passphrase, 2048, 64, OpenSSL::Digest::SHA512.new).bth end
ruby
def to_seed(mnemonic, passphrase: '') to_entropy(mnemonic) OpenSSL::PKCS5.pbkdf2_hmac(mnemonic.join(' ').downcase, 'mnemonic' + passphrase, 2048, 64, OpenSSL::Digest::SHA512.new).bth end
[ "def", "to_seed", "(", "mnemonic", ",", "passphrase", ":", "''", ")", "to_entropy", "(", "mnemonic", ")", "OpenSSL", "::", "PKCS5", ".", "pbkdf2_hmac", "(", "mnemonic", ".", "join", "(", "' '", ")", ".", "downcase", ",", "'mnemonic'", "+", "passphrase", ",", "2048", ",", "64", ",", "OpenSSL", "::", "Digest", "::", "SHA512", ".", "new", ")", ".", "bth", "end" ]
generate seed from mnemonic if mnemonic protected with passphrase, specify that passphrase. @param [Array] mnemonic a array of mnemonic word. @param [String] passphrase a passphrase which protects mnemonic. the default value is an empty string. @return [String] seed
[ "generate", "seed", "from", "mnemonic", "if", "mnemonic", "protected", "with", "passphrase", "specify", "that", "passphrase", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/mnemonic.rb#L54-L58
18,174
chaintope/bitcoinrb
lib/bitcoin/mnemonic.rb
Bitcoin.Mnemonic.checksum
def checksum(entropy) b = Bitcoin.sha256([entropy].pack('B*')).unpack('B*').first b.slice(0, (entropy.length/32)) end
ruby
def checksum(entropy) b = Bitcoin.sha256([entropy].pack('B*')).unpack('B*').first b.slice(0, (entropy.length/32)) end
[ "def", "checksum", "(", "entropy", ")", "b", "=", "Bitcoin", ".", "sha256", "(", "[", "entropy", "]", ".", "pack", "(", "'B*'", ")", ")", ".", "unpack", "(", "'B*'", ")", ".", "first", "b", ".", "slice", "(", "0", ",", "(", "entropy", ".", "length", "/", "32", ")", ")", "end" ]
calculate entropy checksum @param [String] entropy an entropy with bit string format @return [String] an entropy checksum with bit string format
[ "calculate", "entropy", "checksum" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/mnemonic.rb#L63-L66
18,175
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.to_wif
def to_wif version = Bitcoin.chain_params.privkey_version hex = version + priv_key hex += '01' if compressed? hex += Bitcoin.calc_checksum(hex) Base58.encode(hex) end
ruby
def to_wif version = Bitcoin.chain_params.privkey_version hex = version + priv_key hex += '01' if compressed? hex += Bitcoin.calc_checksum(hex) Base58.encode(hex) end
[ "def", "to_wif", "version", "=", "Bitcoin", ".", "chain_params", ".", "privkey_version", "hex", "=", "version", "+", "priv_key", "hex", "+=", "'01'", "if", "compressed?", "hex", "+=", "Bitcoin", ".", "calc_checksum", "(", "hex", ")", "Base58", ".", "encode", "(", "hex", ")", "end" ]
export private key with wif format
[ "export", "private", "key", "with", "wif", "format" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L80-L86
18,176
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.sign
def sign(data, low_r = true, extra_entropy = nil) sig = secp256k1_module.sign_data(data, priv_key, extra_entropy) if low_r && !sig_has_low_r?(sig) counter = 1 until sig_has_low_r?(sig) extra_entropy = [counter].pack('I*').bth.ljust(64, '0').htb sig = secp256k1_module.sign_data(data, priv_key, extra_entropy) counter += 1 end end sig end
ruby
def sign(data, low_r = true, extra_entropy = nil) sig = secp256k1_module.sign_data(data, priv_key, extra_entropy) if low_r && !sig_has_low_r?(sig) counter = 1 until sig_has_low_r?(sig) extra_entropy = [counter].pack('I*').bth.ljust(64, '0').htb sig = secp256k1_module.sign_data(data, priv_key, extra_entropy) counter += 1 end end sig end
[ "def", "sign", "(", "data", ",", "low_r", "=", "true", ",", "extra_entropy", "=", "nil", ")", "sig", "=", "secp256k1_module", ".", "sign_data", "(", "data", ",", "priv_key", ",", "extra_entropy", ")", "if", "low_r", "&&", "!", "sig_has_low_r?", "(", "sig", ")", "counter", "=", "1", "until", "sig_has_low_r?", "(", "sig", ")", "extra_entropy", "=", "[", "counter", "]", ".", "pack", "(", "'I*'", ")", ".", "bth", ".", "ljust", "(", "64", ",", "'0'", ")", ".", "htb", "sig", "=", "secp256k1_module", ".", "sign_data", "(", "data", ",", "priv_key", ",", "extra_entropy", ")", "counter", "+=", "1", "end", "end", "sig", "end" ]
sign +data+ with private key @param [String] data a data to be signed with binary format @param [Boolean] low_r flag to apply low-R. @param [String] extra_entropy the extra entropy for rfc6979. @return [String] signature data with binary format
[ "sign", "+", "data", "+", "with", "private", "key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L93-L104
18,177
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.verify
def verify(sig, origin) return false unless valid_pubkey? begin sig = ecdsa_signature_parse_der_lax(sig) secp256k1_module.verify_sig(origin, sig, pubkey) rescue Exception false end end
ruby
def verify(sig, origin) return false unless valid_pubkey? begin sig = ecdsa_signature_parse_der_lax(sig) secp256k1_module.verify_sig(origin, sig, pubkey) rescue Exception false end end
[ "def", "verify", "(", "sig", ",", "origin", ")", "return", "false", "unless", "valid_pubkey?", "begin", "sig", "=", "ecdsa_signature_parse_der_lax", "(", "sig", ")", "secp256k1_module", ".", "verify_sig", "(", "origin", ",", "sig", ",", "pubkey", ")", "rescue", "Exception", "false", "end", "end" ]
verify signature using public key @param [String] sig signature data with binary format @param [String] origin original message @return [Boolean] verify result
[ "verify", "signature", "using", "public", "key" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L110-L118
18,178
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.to_point
def to_point p = pubkey p ||= generate_pubkey(priv_key, compressed: compressed) ECDSA::Format::PointOctetString.decode(p.htb, Bitcoin::Secp256k1::GROUP) end
ruby
def to_point p = pubkey p ||= generate_pubkey(priv_key, compressed: compressed) ECDSA::Format::PointOctetString.decode(p.htb, Bitcoin::Secp256k1::GROUP) end
[ "def", "to_point", "p", "=", "pubkey", "p", "||=", "generate_pubkey", "(", "priv_key", ",", "compressed", ":", "compressed", ")", "ECDSA", "::", "Format", "::", "PointOctetString", ".", "decode", "(", "p", ".", "htb", ",", "Bitcoin", "::", "Secp256k1", "::", "GROUP", ")", "end" ]
generate pubkey ec point @return [ECDSA::Point]
[ "generate", "pubkey", "ec", "point" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L149-L153
18,179
chaintope/bitcoinrb
lib/bitcoin/key.rb
Bitcoin.Key.ecdsa_signature_parse_der_lax
def ecdsa_signature_parse_der_lax(sig) sig_array = sig.unpack('C*') len_r = sig_array[3] r = sig_array[4...(len_r+4)].pack('C*').bth len_s = sig_array[len_r + 5] s = sig_array[(len_r + 6)...(len_r + 6 + len_s)].pack('C*').bth ECDSA::Signature.new(r.to_i(16), s.to_i(16)).to_der end
ruby
def ecdsa_signature_parse_der_lax(sig) sig_array = sig.unpack('C*') len_r = sig_array[3] r = sig_array[4...(len_r+4)].pack('C*').bth len_s = sig_array[len_r + 5] s = sig_array[(len_r + 6)...(len_r + 6 + len_s)].pack('C*').bth ECDSA::Signature.new(r.to_i(16), s.to_i(16)).to_der end
[ "def", "ecdsa_signature_parse_der_lax", "(", "sig", ")", "sig_array", "=", "sig", ".", "unpack", "(", "'C*'", ")", "len_r", "=", "sig_array", "[", "3", "]", "r", "=", "sig_array", "[", "4", "...", "(", "len_r", "+", "4", ")", "]", ".", "pack", "(", "'C*'", ")", ".", "bth", "len_s", "=", "sig_array", "[", "len_r", "+", "5", "]", "s", "=", "sig_array", "[", "(", "len_r", "+", "6", ")", "...", "(", "len_r", "+", "6", "+", "len_s", ")", "]", ".", "pack", "(", "'C*'", ")", ".", "bth", "ECDSA", "::", "Signature", ".", "new", "(", "r", ".", "to_i", "(", "16", ")", ",", "s", ".", "to_i", "(", "16", ")", ")", ".", "to_der", "end" ]
Supported violations include negative integers, excessive padding, garbage at the end, and overly long length descriptors. This is safe to use in Bitcoin because since the activation of BIP66, signatures are verified to be strict DER before being passed to this module, and we know it supports all violations present in the blockchain before that point.
[ "Supported", "violations", "include", "negative", "integers", "excessive", "padding", "garbage", "at", "the", "end", "and", "overly", "long", "length", "descriptors", ".", "This", "is", "safe", "to", "use", "in", "Bitcoin", "because", "since", "the", "activation", "of", "BIP66", "signatures", "are", "verified", "to", "be", "strict", "DER", "before", "being", "passed", "to", "this", "module", "and", "we", "know", "it", "supports", "all", "violations", "present", "in", "the", "blockchain", "before", "that", "point", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/key.rb#L270-L277
18,180
chaintope/bitcoinrb
lib/bitcoin/base58.rb
Bitcoin.Base58.encode
def encode(hex) leading_zero_bytes = (hex.match(/^([0]+)/) ? $1 : '').size / 2 int_val = hex.to_i(16) base58_val = '' while int_val > 0 int_val, remainder = int_val.divmod(SIZE) base58_val = ALPHABET[remainder] + base58_val end ('1' * leading_zero_bytes) + base58_val end
ruby
def encode(hex) leading_zero_bytes = (hex.match(/^([0]+)/) ? $1 : '').size / 2 int_val = hex.to_i(16) base58_val = '' while int_val > 0 int_val, remainder = int_val.divmod(SIZE) base58_val = ALPHABET[remainder] + base58_val end ('1' * leading_zero_bytes) + base58_val end
[ "def", "encode", "(", "hex", ")", "leading_zero_bytes", "=", "(", "hex", ".", "match", "(", "/", "/", ")", "?", "$1", ":", "''", ")", ".", "size", "/", "2", "int_val", "=", "hex", ".", "to_i", "(", "16", ")", "base58_val", "=", "''", "while", "int_val", ">", "0", "int_val", ",", "remainder", "=", "int_val", ".", "divmod", "(", "SIZE", ")", "base58_val", "=", "ALPHABET", "[", "remainder", "]", "+", "base58_val", "end", "(", "'1'", "*", "leading_zero_bytes", ")", "+", "base58_val", "end" ]
encode hex value to base58 string.
[ "encode", "hex", "value", "to", "base58", "string", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/base58.rb#L12-L21
18,181
chaintope/bitcoinrb
lib/bitcoin/base58.rb
Bitcoin.Base58.decode
def decode(base58_val) int_val = 0 base58_val.reverse.split(//).each_with_index do |char,index| raise ArgumentError, 'Value passed not a valid Base58 String.' if (char_index = ALPHABET.index(char)).nil? int_val += char_index * (SIZE ** index) end s = int_val.to_even_length_hex s = '' if s == '00' leading_zero_bytes = (base58_val.match(/^([1]+)/) ? $1 : '').size s = ('00' * leading_zero_bytes) + s if leading_zero_bytes > 0 s end
ruby
def decode(base58_val) int_val = 0 base58_val.reverse.split(//).each_with_index do |char,index| raise ArgumentError, 'Value passed not a valid Base58 String.' if (char_index = ALPHABET.index(char)).nil? int_val += char_index * (SIZE ** index) end s = int_val.to_even_length_hex s = '' if s == '00' leading_zero_bytes = (base58_val.match(/^([1]+)/) ? $1 : '').size s = ('00' * leading_zero_bytes) + s if leading_zero_bytes > 0 s end
[ "def", "decode", "(", "base58_val", ")", "int_val", "=", "0", "base58_val", ".", "reverse", ".", "split", "(", "/", "/", ")", ".", "each_with_index", "do", "|", "char", ",", "index", "|", "raise", "ArgumentError", ",", "'Value passed not a valid Base58 String.'", "if", "(", "char_index", "=", "ALPHABET", ".", "index", "(", "char", ")", ")", ".", "nil?", "int_val", "+=", "char_index", "*", "(", "SIZE", "**", "index", ")", "end", "s", "=", "int_val", ".", "to_even_length_hex", "s", "=", "''", "if", "s", "==", "'00'", "leading_zero_bytes", "=", "(", "base58_val", ".", "match", "(", "/", "/", ")", "?", "$1", ":", "''", ")", ".", "size", "s", "=", "(", "'00'", "*", "leading_zero_bytes", ")", "+", "s", "if", "leading_zero_bytes", ">", "0", "s", "end" ]
decode base58 string to hex value.
[ "decode", "base58", "string", "to", "hex", "value", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/base58.rb#L24-L35
18,182
chaintope/bitcoinrb
lib/bitcoin/block.rb
Bitcoin.Block.calculate_witness_commitment
def calculate_witness_commitment witness_hashes = [COINBASE_WTXID] witness_hashes += (transactions[1..-1].map(&:witness_hash)) reserved_value = transactions[0].inputs[0].script_witness.stack.map(&:bth).join root_hash = Bitcoin::MerkleTree.build_from_leaf(witness_hashes).merkle_root Bitcoin.double_sha256([root_hash + reserved_value].pack('H*')).bth end
ruby
def calculate_witness_commitment witness_hashes = [COINBASE_WTXID] witness_hashes += (transactions[1..-1].map(&:witness_hash)) reserved_value = transactions[0].inputs[0].script_witness.stack.map(&:bth).join root_hash = Bitcoin::MerkleTree.build_from_leaf(witness_hashes).merkle_root Bitcoin.double_sha256([root_hash + reserved_value].pack('H*')).bth end
[ "def", "calculate_witness_commitment", "witness_hashes", "=", "[", "COINBASE_WTXID", "]", "witness_hashes", "+=", "(", "transactions", "[", "1", "..", "-", "1", "]", ".", "map", "(", ":witness_hash", ")", ")", "reserved_value", "=", "transactions", "[", "0", "]", ".", "inputs", "[", "0", "]", ".", "script_witness", ".", "stack", ".", "map", "(", ":bth", ")", ".", "join", "root_hash", "=", "Bitcoin", "::", "MerkleTree", ".", "build_from_leaf", "(", "witness_hashes", ")", ".", "merkle_root", "Bitcoin", ".", "double_sha256", "(", "[", "root_hash", "+", "reserved_value", "]", ".", "pack", "(", "'H*'", ")", ")", ".", "bth", "end" ]
calculate witness commitment from tx list.
[ "calculate", "witness", "commitment", "from", "tx", "list", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/block.rb#L57-L63
18,183
chaintope/bitcoinrb
lib/bitcoin/block.rb
Bitcoin.Block.height
def height return nil if header.version < 2 coinbase_tx = transactions[0] return nil unless coinbase_tx.coinbase_tx? buf = StringIO.new(coinbase_tx.inputs[0].script_sig.to_payload) len = Bitcoin.unpack_var_int_from_io(buf) buf.read(len).reverse.bth.to_i(16) end
ruby
def height return nil if header.version < 2 coinbase_tx = transactions[0] return nil unless coinbase_tx.coinbase_tx? buf = StringIO.new(coinbase_tx.inputs[0].script_sig.to_payload) len = Bitcoin.unpack_var_int_from_io(buf) buf.read(len).reverse.bth.to_i(16) end
[ "def", "height", "return", "nil", "if", "header", ".", "version", "<", "2", "coinbase_tx", "=", "transactions", "[", "0", "]", "return", "nil", "unless", "coinbase_tx", ".", "coinbase_tx?", "buf", "=", "StringIO", ".", "new", "(", "coinbase_tx", ".", "inputs", "[", "0", "]", ".", "script_sig", ".", "to_payload", ")", "len", "=", "Bitcoin", ".", "unpack_var_int_from_io", "(", "buf", ")", "buf", ".", "read", "(", "len", ")", ".", "reverse", ".", "bth", ".", "to_i", "(", "16", ")", "end" ]
return this block height. block height is included in coinbase. if block version under 1, height does not include in coinbase, so return nil.
[ "return", "this", "block", "height", ".", "block", "height", "is", "included", "in", "coinbase", ".", "if", "block", "version", "under", "1", "height", "does", "not", "include", "in", "coinbase", "so", "return", "nil", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/block.rb#L67-L74
18,184
chaintope/bitcoinrb
lib/openassets/payload.rb
OpenAssets.Payload.to_payload
def to_payload payload = String.new payload << MARKER payload << VERSION payload << Bitcoin.pack_var_int(quantities.size) << quantities.map{|q| LEB128.encode_unsigned(q).read }.join payload << Bitcoin.pack_var_int(metadata.length) << metadata.bytes.map{|b| sprintf("%02x", b)}.join.htb payload end
ruby
def to_payload payload = String.new payload << MARKER payload << VERSION payload << Bitcoin.pack_var_int(quantities.size) << quantities.map{|q| LEB128.encode_unsigned(q).read }.join payload << Bitcoin.pack_var_int(metadata.length) << metadata.bytes.map{|b| sprintf("%02x", b)}.join.htb payload end
[ "def", "to_payload", "payload", "=", "String", ".", "new", "payload", "<<", "MARKER", "payload", "<<", "VERSION", "payload", "<<", "Bitcoin", ".", "pack_var_int", "(", "quantities", ".", "size", ")", "<<", "quantities", ".", "map", "{", "|", "q", "|", "LEB128", ".", "encode_unsigned", "(", "q", ")", ".", "read", "}", ".", "join", "payload", "<<", "Bitcoin", ".", "pack_var_int", "(", "metadata", ".", "length", ")", "<<", "metadata", ".", "bytes", ".", "map", "{", "|", "b", "|", "sprintf", "(", "\"%02x\"", ",", "b", ")", "}", ".", "join", ".", "htb", "payload", "end" ]
generate binary payload
[ "generate", "binary", "payload" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/openassets/payload.rb#L43-L50
18,185
chaintope/bitcoinrb
lib/bitcoin/util.rb
Bitcoin.Util.hash160
def hash160(hex) Digest::RMD160.hexdigest(Digest::SHA256.digest(hex.htb)) end
ruby
def hash160(hex) Digest::RMD160.hexdigest(Digest::SHA256.digest(hex.htb)) end
[ "def", "hash160", "(", "hex", ")", "Digest", "::", "RMD160", ".", "hexdigest", "(", "Digest", "::", "SHA256", ".", "digest", "(", "hex", ".", "htb", ")", ")", "end" ]
generate sha256-ripemd160 hash for value
[ "generate", "sha256", "-", "ripemd160", "hash", "for", "value" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/util.rb#L86-L88
18,186
chaintope/bitcoinrb
lib/bitcoin/util.rb
Bitcoin.Util.encode_base58_address
def encode_base58_address(hex, addr_version) base = addr_version + hex Base58.encode(base + calc_checksum(base)) end
ruby
def encode_base58_address(hex, addr_version) base = addr_version + hex Base58.encode(base + calc_checksum(base)) end
[ "def", "encode_base58_address", "(", "hex", ",", "addr_version", ")", "base", "=", "addr_version", "+", "hex", "Base58", ".", "encode", "(", "base", "+", "calc_checksum", "(", "base", ")", ")", "end" ]
encode Base58 check address. @param [String] hex the address payload. @param [String] addr_version the address version for P2PKH and P2SH. @return [String] Base58 check encoding address.
[ "encode", "Base58", "check", "address", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/util.rb#L94-L97
18,187
chaintope/bitcoinrb
lib/bitcoin/util.rb
Bitcoin.Util.decode_base58_address
def decode_base58_address(addr) hex = Base58.decode(addr) if hex.size == 50 && calc_checksum(hex[0...-8]) == hex[-8..-1] raise 'Invalid version bytes.' unless [Bitcoin.chain_params.address_version, Bitcoin.chain_params.p2sh_version].include?(hex[0..1]) [hex[2...-8], hex[0..1]] else raise 'Invalid address.' end end
ruby
def decode_base58_address(addr) hex = Base58.decode(addr) if hex.size == 50 && calc_checksum(hex[0...-8]) == hex[-8..-1] raise 'Invalid version bytes.' unless [Bitcoin.chain_params.address_version, Bitcoin.chain_params.p2sh_version].include?(hex[0..1]) [hex[2...-8], hex[0..1]] else raise 'Invalid address.' end end
[ "def", "decode_base58_address", "(", "addr", ")", "hex", "=", "Base58", ".", "decode", "(", "addr", ")", "if", "hex", ".", "size", "==", "50", "&&", "calc_checksum", "(", "hex", "[", "0", "...", "-", "8", "]", ")", "==", "hex", "[", "-", "8", "..", "-", "1", "]", "raise", "'Invalid version bytes.'", "unless", "[", "Bitcoin", ".", "chain_params", ".", "address_version", ",", "Bitcoin", ".", "chain_params", ".", "p2sh_version", "]", ".", "include?", "(", "hex", "[", "0", "..", "1", "]", ")", "[", "hex", "[", "2", "...", "-", "8", "]", ",", "hex", "[", "0", "..", "1", "]", "]", "else", "raise", "'Invalid address.'", "end", "end" ]
decode Base58 check encoding address. @param [String] addr address. @return [Array] hex and address version
[ "decode", "Base58", "check", "encoding", "address", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/util.rb#L102-L110
18,188
chaintope/bitcoinrb
lib/bitcoin/validation.rb
Bitcoin.Validation.check_tx
def check_tx(tx, state) # Basic checks that don't depend on any context if tx.inputs.empty? return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vin-empty') end if tx.outputs.empty? return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-empty') end # Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability) if tx.serialize_old_format.bytesize * Bitcoin::WITNESS_SCALE_FACTOR > Bitcoin::MAX_BLOCK_WEIGHT return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-oversize') end # Check for negative or overflow output values amount = 0 tx.outputs.each do |o| return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-negative') if o.value < 0 return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < o.value amount += o.value return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < amount end # Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock out_points = tx.inputs.map{|i|i.out_point.to_payload} unless out_points.size == out_points.uniq.size return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-inputs-duplicate') end if tx.coinbase_tx? if tx.inputs[0].script_sig.size < 2 || tx.inputs[0].script_sig.size > 100 return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-cb-length') end else tx.inputs.each do |i| if i.out_point.nil? || !i.out_point.valid? return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-prevout-null') end end end true end
ruby
def check_tx(tx, state) # Basic checks that don't depend on any context if tx.inputs.empty? return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vin-empty') end if tx.outputs.empty? return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-empty') end # Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability) if tx.serialize_old_format.bytesize * Bitcoin::WITNESS_SCALE_FACTOR > Bitcoin::MAX_BLOCK_WEIGHT return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-oversize') end # Check for negative or overflow output values amount = 0 tx.outputs.each do |o| return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-negative') if o.value < 0 return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < o.value amount += o.value return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-vout-toolarge') if MAX_MONEY < amount end # Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock out_points = tx.inputs.map{|i|i.out_point.to_payload} unless out_points.size == out_points.uniq.size return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-inputs-duplicate') end if tx.coinbase_tx? if tx.inputs[0].script_sig.size < 2 || tx.inputs[0].script_sig.size > 100 return state.DoS(100, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-cb-length') end else tx.inputs.each do |i| if i.out_point.nil? || !i.out_point.valid? return state.DoS(10, reject_code: Message::Reject::CODE_INVALID, reject_reason: 'bad-txns-prevout-null') end end end true end
[ "def", "check_tx", "(", "tx", ",", "state", ")", "# Basic checks that don't depend on any context", "if", "tx", ".", "inputs", ".", "empty?", "return", "state", ".", "DoS", "(", "10", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vin-empty'", ")", "end", "if", "tx", ".", "outputs", ".", "empty?", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vout-empty'", ")", "end", "# Size limits (this doesn't take the witness into account, as that hasn't been checked for malleability)", "if", "tx", ".", "serialize_old_format", ".", "bytesize", "*", "Bitcoin", "::", "WITNESS_SCALE_FACTOR", ">", "Bitcoin", "::", "MAX_BLOCK_WEIGHT", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-oversize'", ")", "end", "# Check for negative or overflow output values", "amount", "=", "0", "tx", ".", "outputs", ".", "each", "do", "|", "o", "|", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vout-negative'", ")", "if", "o", ".", "value", "<", "0", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vout-toolarge'", ")", "if", "MAX_MONEY", "<", "o", ".", "value", "amount", "+=", "o", ".", "value", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-vout-toolarge'", ")", "if", "MAX_MONEY", "<", "amount", "end", "# Check for duplicate inputs - note that this check is slow so we skip it in CheckBlock", "out_points", "=", "tx", ".", "inputs", ".", "map", "{", "|", "i", "|", "i", ".", "out_point", ".", "to_payload", "}", "unless", "out_points", ".", "size", "==", "out_points", ".", "uniq", ".", "size", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-inputs-duplicate'", ")", "end", "if", "tx", ".", "coinbase_tx?", "if", "tx", ".", "inputs", "[", "0", "]", ".", "script_sig", ".", "size", "<", "2", "||", "tx", ".", "inputs", "[", "0", "]", ".", "script_sig", ".", "size", ">", "100", "return", "state", ".", "DoS", "(", "100", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-cb-length'", ")", "end", "else", "tx", ".", "inputs", ".", "each", "do", "|", "i", "|", "if", "i", ".", "out_point", ".", "nil?", "||", "!", "i", ".", "out_point", ".", "valid?", "return", "state", ".", "DoS", "(", "10", ",", "reject_code", ":", "Message", "::", "Reject", "::", "CODE_INVALID", ",", "reject_reason", ":", "'bad-txns-prevout-null'", ")", "end", "end", "end", "true", "end" ]
check transaction validation
[ "check", "transaction", "validation" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/validation.rb#L6-L48
18,189
chaintope/bitcoinrb
lib/bitcoin/script/script_interpreter.rb
Bitcoin.ScriptInterpreter.verify_script
def verify_script(script_sig, script_pubkey, witness = ScriptWitness.new) return set_error(SCRIPT_ERR_SIG_PUSHONLY) if flag?(SCRIPT_VERIFY_SIGPUSHONLY) && !script_sig.push_only? stack_copy = nil had_witness = false return false unless eval_script(script_sig, :base) stack_copy = stack.dup if flag?(SCRIPT_VERIFY_P2SH) return false unless eval_script(script_pubkey, :base) return set_error(SCRIPT_ERR_EVAL_FALSE) if stack.empty? || !cast_to_bool(stack.last.htb) # Bare witness programs if flag?(SCRIPT_VERIFY_WITNESS) && script_pubkey.witness_program? had_witness = true return set_error(SCRIPT_ERR_WITNESS_MALLEATED) unless script_sig.size == 0 version, program = script_pubkey.witness_data stack_copy = stack.dup return false unless verify_witness_program(witness, version, program) end # Additional validation for spend-to-script-hash transactions if flag?(SCRIPT_VERIFY_P2SH) && script_pubkey.p2sh? return set_error(SCRIPT_ERR_SIG_PUSHONLY) unless script_sig.push_only? tmp = stack @stack = stack_copy raise 'stack cannot be empty.' if stack.empty? begin redeem_script = Bitcoin::Script.parse_from_payload(stack.pop.htb) rescue Exception => e return set_error(SCRIPT_ERR_BAD_OPCODE, "Failed to parse serialized redeem script for P2SH. #{e.message}") end return false unless eval_script(redeem_script, :base) return set_error(SCRIPT_ERR_EVAL_FALSE) if stack.empty? || !cast_to_bool(stack.last) # P2SH witness program if flag?(SCRIPT_VERIFY_WITNESS) && redeem_script.witness_program? had_witness = true # The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we reintroduce malleability. return set_error(SCRIPT_ERR_WITNESS_MALLEATED_P2SH) unless script_sig == (Bitcoin::Script.new << redeem_script.to_payload.bth) version, program = redeem_script.witness_data return false unless verify_witness_program(witness, version, program) end end # The CLEANSTACK check is only performed after potential P2SH evaluation, # as the non-P2SH evaluation of a P2SH script will obviously not result in a clean stack (the P2SH inputs remain). # The same holds for witness evaluation. if flag?(SCRIPT_VERIFY_CLEANSTACK) # Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK would be possible, # which is not a softfork (and P2SH should be one). raise 'assert' unless flag?(SCRIPT_VERIFY_P2SH) return set_error(SCRIPT_ERR_CLEANSTACK) unless stack.size == 1 end if flag?(SCRIPT_VERIFY_WITNESS) raise 'assert' unless flag?(SCRIPT_VERIFY_P2SH) return set_error(SCRIPT_ERR_WITNESS_UNEXPECTED) if !had_witness && !witness.empty? end true end
ruby
def verify_script(script_sig, script_pubkey, witness = ScriptWitness.new) return set_error(SCRIPT_ERR_SIG_PUSHONLY) if flag?(SCRIPT_VERIFY_SIGPUSHONLY) && !script_sig.push_only? stack_copy = nil had_witness = false return false unless eval_script(script_sig, :base) stack_copy = stack.dup if flag?(SCRIPT_VERIFY_P2SH) return false unless eval_script(script_pubkey, :base) return set_error(SCRIPT_ERR_EVAL_FALSE) if stack.empty? || !cast_to_bool(stack.last.htb) # Bare witness programs if flag?(SCRIPT_VERIFY_WITNESS) && script_pubkey.witness_program? had_witness = true return set_error(SCRIPT_ERR_WITNESS_MALLEATED) unless script_sig.size == 0 version, program = script_pubkey.witness_data stack_copy = stack.dup return false unless verify_witness_program(witness, version, program) end # Additional validation for spend-to-script-hash transactions if flag?(SCRIPT_VERIFY_P2SH) && script_pubkey.p2sh? return set_error(SCRIPT_ERR_SIG_PUSHONLY) unless script_sig.push_only? tmp = stack @stack = stack_copy raise 'stack cannot be empty.' if stack.empty? begin redeem_script = Bitcoin::Script.parse_from_payload(stack.pop.htb) rescue Exception => e return set_error(SCRIPT_ERR_BAD_OPCODE, "Failed to parse serialized redeem script for P2SH. #{e.message}") end return false unless eval_script(redeem_script, :base) return set_error(SCRIPT_ERR_EVAL_FALSE) if stack.empty? || !cast_to_bool(stack.last) # P2SH witness program if flag?(SCRIPT_VERIFY_WITNESS) && redeem_script.witness_program? had_witness = true # The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we reintroduce malleability. return set_error(SCRIPT_ERR_WITNESS_MALLEATED_P2SH) unless script_sig == (Bitcoin::Script.new << redeem_script.to_payload.bth) version, program = redeem_script.witness_data return false unless verify_witness_program(witness, version, program) end end # The CLEANSTACK check is only performed after potential P2SH evaluation, # as the non-P2SH evaluation of a P2SH script will obviously not result in a clean stack (the P2SH inputs remain). # The same holds for witness evaluation. if flag?(SCRIPT_VERIFY_CLEANSTACK) # Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK would be possible, # which is not a softfork (and P2SH should be one). raise 'assert' unless flag?(SCRIPT_VERIFY_P2SH) return set_error(SCRIPT_ERR_CLEANSTACK) unless stack.size == 1 end if flag?(SCRIPT_VERIFY_WITNESS) raise 'assert' unless flag?(SCRIPT_VERIFY_P2SH) return set_error(SCRIPT_ERR_WITNESS_UNEXPECTED) if !had_witness && !witness.empty? end true end
[ "def", "verify_script", "(", "script_sig", ",", "script_pubkey", ",", "witness", "=", "ScriptWitness", ".", "new", ")", "return", "set_error", "(", "SCRIPT_ERR_SIG_PUSHONLY", ")", "if", "flag?", "(", "SCRIPT_VERIFY_SIGPUSHONLY", ")", "&&", "!", "script_sig", ".", "push_only?", "stack_copy", "=", "nil", "had_witness", "=", "false", "return", "false", "unless", "eval_script", "(", "script_sig", ",", ":base", ")", "stack_copy", "=", "stack", ".", "dup", "if", "flag?", "(", "SCRIPT_VERIFY_P2SH", ")", "return", "false", "unless", "eval_script", "(", "script_pubkey", ",", ":base", ")", "return", "set_error", "(", "SCRIPT_ERR_EVAL_FALSE", ")", "if", "stack", ".", "empty?", "||", "!", "cast_to_bool", "(", "stack", ".", "last", ".", "htb", ")", "# Bare witness programs", "if", "flag?", "(", "SCRIPT_VERIFY_WITNESS", ")", "&&", "script_pubkey", ".", "witness_program?", "had_witness", "=", "true", "return", "set_error", "(", "SCRIPT_ERR_WITNESS_MALLEATED", ")", "unless", "script_sig", ".", "size", "==", "0", "version", ",", "program", "=", "script_pubkey", ".", "witness_data", "stack_copy", "=", "stack", ".", "dup", "return", "false", "unless", "verify_witness_program", "(", "witness", ",", "version", ",", "program", ")", "end", "# Additional validation for spend-to-script-hash transactions", "if", "flag?", "(", "SCRIPT_VERIFY_P2SH", ")", "&&", "script_pubkey", ".", "p2sh?", "return", "set_error", "(", "SCRIPT_ERR_SIG_PUSHONLY", ")", "unless", "script_sig", ".", "push_only?", "tmp", "=", "stack", "@stack", "=", "stack_copy", "raise", "'stack cannot be empty.'", "if", "stack", ".", "empty?", "begin", "redeem_script", "=", "Bitcoin", "::", "Script", ".", "parse_from_payload", "(", "stack", ".", "pop", ".", "htb", ")", "rescue", "Exception", "=>", "e", "return", "set_error", "(", "SCRIPT_ERR_BAD_OPCODE", ",", "\"Failed to parse serialized redeem script for P2SH. #{e.message}\"", ")", "end", "return", "false", "unless", "eval_script", "(", "redeem_script", ",", ":base", ")", "return", "set_error", "(", "SCRIPT_ERR_EVAL_FALSE", ")", "if", "stack", ".", "empty?", "||", "!", "cast_to_bool", "(", "stack", ".", "last", ")", "# P2SH witness program", "if", "flag?", "(", "SCRIPT_VERIFY_WITNESS", ")", "&&", "redeem_script", ".", "witness_program?", "had_witness", "=", "true", "# The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we reintroduce malleability.", "return", "set_error", "(", "SCRIPT_ERR_WITNESS_MALLEATED_P2SH", ")", "unless", "script_sig", "==", "(", "Bitcoin", "::", "Script", ".", "new", "<<", "redeem_script", ".", "to_payload", ".", "bth", ")", "version", ",", "program", "=", "redeem_script", ".", "witness_data", "return", "false", "unless", "verify_witness_program", "(", "witness", ",", "version", ",", "program", ")", "end", "end", "# The CLEANSTACK check is only performed after potential P2SH evaluation,", "# as the non-P2SH evaluation of a P2SH script will obviously not result in a clean stack (the P2SH inputs remain).", "# The same holds for witness evaluation.", "if", "flag?", "(", "SCRIPT_VERIFY_CLEANSTACK", ")", "# Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK would be possible,", "# which is not a softfork (and P2SH should be one).", "raise", "'assert'", "unless", "flag?", "(", "SCRIPT_VERIFY_P2SH", ")", "return", "set_error", "(", "SCRIPT_ERR_CLEANSTACK", ")", "unless", "stack", ".", "size", "==", "1", "end", "if", "flag?", "(", "SCRIPT_VERIFY_WITNESS", ")", "raise", "'assert'", "unless", "flag?", "(", "SCRIPT_VERIFY_P2SH", ")", "return", "set_error", "(", "SCRIPT_ERR_WITNESS_UNEXPECTED", ")", "if", "!", "had_witness", "&&", "!", "witness", ".", "empty?", "end", "true", "end" ]
initialize runner eval script @param [Bitcoin::Script] script_sig a signature script (unlock script which data push only) @param [Bitcoin::Script] script_pubkey a script pubkey (locking script) @param [Bitcoin::ScriptWitness] witness a witness script @return [Boolean] result
[ "initialize", "runner", "eval", "script" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script_interpreter.rb#L37-L102
18,190
chaintope/bitcoinrb
lib/bitcoin/script/script_interpreter.rb
Bitcoin.ScriptInterpreter.pop_int
def pop_int(count = 1) i = stack.pop(count).map{ |s| cast_to_int(s) } count == 1 ? i.first : i end
ruby
def pop_int(count = 1) i = stack.pop(count).map{ |s| cast_to_int(s) } count == 1 ? i.first : i end
[ "def", "pop_int", "(", "count", "=", "1", ")", "i", "=", "stack", ".", "pop", "(", "count", ")", ".", "map", "{", "|", "s", "|", "cast_to_int", "(", "s", ")", "}", "count", "==", "1", "?", "i", ".", "first", ":", "i", "end" ]
pop the item with the int value for the number specified by +count+ from the stack.
[ "pop", "the", "item", "with", "the", "int", "value", "for", "the", "number", "specified", "by", "+", "count", "+", "from", "the", "stack", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script_interpreter.rb#L534-L537
18,191
chaintope/bitcoinrb
lib/bitcoin/script/script_interpreter.rb
Bitcoin.ScriptInterpreter.cast_to_int
def cast_to_int(s, max_num_size = DEFAULT_MAX_NUM_SIZE) data = s.htb raise '"script number overflow"' if data.bytesize > max_num_size if require_minimal && data.bytesize > 0 if data.bytes[-1] & 0x7f == 0 && (data.bytesize <= 1 || data.bytes[data.bytesize - 2] & 0x80 == 0) raise 'non-minimally encoded script number' end end Script.decode_number(s) end
ruby
def cast_to_int(s, max_num_size = DEFAULT_MAX_NUM_SIZE) data = s.htb raise '"script number overflow"' if data.bytesize > max_num_size if require_minimal && data.bytesize > 0 if data.bytes[-1] & 0x7f == 0 && (data.bytesize <= 1 || data.bytes[data.bytesize - 2] & 0x80 == 0) raise 'non-minimally encoded script number' end end Script.decode_number(s) end
[ "def", "cast_to_int", "(", "s", ",", "max_num_size", "=", "DEFAULT_MAX_NUM_SIZE", ")", "data", "=", "s", ".", "htb", "raise", "'\"script number overflow\"'", "if", "data", ".", "bytesize", ">", "max_num_size", "if", "require_minimal", "&&", "data", ".", "bytesize", ">", "0", "if", "data", ".", "bytes", "[", "-", "1", "]", "&", "0x7f", "==", "0", "&&", "(", "data", ".", "bytesize", "<=", "1", "||", "data", ".", "bytes", "[", "data", ".", "bytesize", "-", "2", "]", "&", "0x80", "==", "0", ")", "raise", "'non-minimally encoded script number'", "end", "end", "Script", ".", "decode_number", "(", "s", ")", "end" ]
cast item to int value.
[ "cast", "item", "to", "int", "value", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/script/script_interpreter.rb#L540-L549
18,192
chaintope/bitcoinrb
lib/bitcoin/bloom_filter.rb
Bitcoin.BloomFilter.contains?
def contains?(data) return true if full? hash_funcs.times do |i| hash = to_hash(data, i) return false unless check_bit(hash) end true end
ruby
def contains?(data) return true if full? hash_funcs.times do |i| hash = to_hash(data, i) return false unless check_bit(hash) end true end
[ "def", "contains?", "(", "data", ")", "return", "true", "if", "full?", "hash_funcs", ".", "times", "do", "|", "i", "|", "hash", "=", "to_hash", "(", "data", ",", "i", ")", "return", "false", "unless", "check_bit", "(", "hash", ")", "end", "true", "end" ]
Returns true if the given data matches the filter @param [String] data The data to check the current filter @return [Boolean] true if the given data matches the filter
[ "Returns", "true", "if", "the", "given", "data", "matches", "the", "filter" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/bloom_filter.rb#L43-L50
18,193
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.hash_to_range
def hash_to_range(element) hash = SipHash.digest(key, element) map_into_range(hash, f) end
ruby
def hash_to_range(element) hash = SipHash.digest(key, element) map_into_range(hash, f) end
[ "def", "hash_to_range", "(", "element", ")", "hash", "=", "SipHash", ".", "digest", "(", "key", ",", "element", ")", "map_into_range", "(", "hash", ",", "f", ")", "end" ]
Hash a data element to an integer in the range [0, F). @param [String] element with binary format. @return [Integer]
[ "Hash", "a", "data", "element", "to", "an", "integer", "in", "the", "range", "[", "0", "F", ")", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L61-L64
18,194
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.match_internal?
def match_internal?(hashes, size) n, payload = Bitcoin.unpack_var_int(encoded.htb) bit_reader = Bitcoin::BitStreamReader.new(payload) value = 0 hashes_index = 0 n.times do delta = golomb_rice_decode(bit_reader, p) value += delta loop do return false if hashes_index == size return true if hashes[hashes_index] == value break if hashes[hashes_index] > value hashes_index += 1 end end false end
ruby
def match_internal?(hashes, size) n, payload = Bitcoin.unpack_var_int(encoded.htb) bit_reader = Bitcoin::BitStreamReader.new(payload) value = 0 hashes_index = 0 n.times do delta = golomb_rice_decode(bit_reader, p) value += delta loop do return false if hashes_index == size return true if hashes[hashes_index] == value break if hashes[hashes_index] > value hashes_index += 1 end end false end
[ "def", "match_internal?", "(", "hashes", ",", "size", ")", "n", ",", "payload", "=", "Bitcoin", ".", "unpack_var_int", "(", "encoded", ".", "htb", ")", "bit_reader", "=", "Bitcoin", "::", "BitStreamReader", ".", "new", "(", "payload", ")", "value", "=", "0", "hashes_index", "=", "0", "n", ".", "times", "do", "delta", "=", "golomb_rice_decode", "(", "bit_reader", ",", "p", ")", "value", "+=", "delta", "loop", "do", "return", "false", "if", "hashes_index", "==", "size", "return", "true", "if", "hashes", "[", "hashes_index", "]", "==", "value", "break", "if", "hashes", "[", "hashes_index", "]", ">", "value", "hashes_index", "+=", "1", "end", "end", "false", "end" ]
Checks if the elements may be in the set. @param [Array[Integer]] hashes the query hash list. @param [Integer] size query size. @return [Boolean] whether elements in set.
[ "Checks", "if", "the", "elements", "may", "be", "in", "the", "set", "." ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L96-L112
18,195
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.golomb_rice_encode
def golomb_rice_encode(bit_writer, p, x) q = x >> p while q > 0 nbits = q <= 64 ? q : 64 bit_writer.write(-1, nbits) # 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp. q -= nbits end bit_writer.write(0, 1) bit_writer.write(x, p) end
ruby
def golomb_rice_encode(bit_writer, p, x) q = x >> p while q > 0 nbits = q <= 64 ? q : 64 bit_writer.write(-1, nbits) # 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp. q -= nbits end bit_writer.write(0, 1) bit_writer.write(x, p) end
[ "def", "golomb_rice_encode", "(", "bit_writer", ",", "p", ",", "x", ")", "q", "=", "x", ">>", "p", "while", "q", ">", "0", "nbits", "=", "q", "<=", "64", "?", "q", ":", "64", "bit_writer", ".", "write", "(", "-", "1", ",", "nbits", ")", "# 18446744073709551615 is 2**64 - 1 = ~0ULL in cpp.", "q", "-=", "nbits", "end", "bit_writer", ".", "write", "(", "0", ",", "1", ")", "bit_writer", ".", "write", "(", "x", ",", "p", ")", "end" ]
encode golomb rice
[ "encode", "golomb", "rice" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L115-L124
18,196
chaintope/bitcoinrb
lib/bitcoin/gcs_filter.rb
Bitcoin.GCSFilter.golomb_rice_decode
def golomb_rice_decode(bit_reader, p) q = 0 while bit_reader.read(1) == 1 q +=1 end r = bit_reader.read(p) (q << p) + r end
ruby
def golomb_rice_decode(bit_reader, p) q = 0 while bit_reader.read(1) == 1 q +=1 end r = bit_reader.read(p) (q << p) + r end
[ "def", "golomb_rice_decode", "(", "bit_reader", ",", "p", ")", "q", "=", "0", "while", "bit_reader", ".", "read", "(", "1", ")", "==", "1", "q", "+=", "1", "end", "r", "=", "bit_reader", ".", "read", "(", "p", ")", "(", "q", "<<", "p", ")", "+", "r", "end" ]
decode golomb rice
[ "decode", "golomb", "rice" ]
39396e4c9815214d6b0ab694fa8326978a7f5438
https://github.com/chaintope/bitcoinrb/blob/39396e4c9815214d6b0ab694fa8326978a7f5438/lib/bitcoin/gcs_filter.rb#L127-L134
18,197
Druwerd/caplock
lib/caplock.rb
Capistrano.Caplock.remote_file_content_same_as?
def remote_file_content_same_as?(full_path, content) Digest::MD5.hexdigest(content) == top.capture("md5sum #{full_path} | awk '{ print $1 }'").strip end
ruby
def remote_file_content_same_as?(full_path, content) Digest::MD5.hexdigest(content) == top.capture("md5sum #{full_path} | awk '{ print $1 }'").strip end
[ "def", "remote_file_content_same_as?", "(", "full_path", ",", "content", ")", "Digest", "::", "MD5", ".", "hexdigest", "(", "content", ")", "==", "top", ".", "capture", "(", "\"md5sum #{full_path} | awk '{ print $1 }'\"", ")", ".", "strip", "end" ]
Returns Boolean value indicating whether the file at +full_path+ matches +content+. Checks if file is equivalent to content by checking whether or not the MD5 of the remote content is the same as the MD5 of the String in +content+.
[ "Returns", "Boolean", "value", "indicating", "whether", "the", "file", "at", "+", "full_path", "+", "matches", "+", "content", "+", ".", "Checks", "if", "file", "is", "equivalent", "to", "content", "by", "checking", "whether", "or", "not", "the", "MD5", "of", "the", "remote", "content", "is", "the", "same", "as", "the", "MD5", "of", "the", "String", "in", "+", "content", "+", "." ]
04525a983abe2e63210d7d605073fdd39c641f73
https://github.com/Druwerd/caplock/blob/04525a983abe2e63210d7d605073fdd39c641f73/lib/caplock.rb#L27-L29
18,198
Druwerd/caplock
lib/caplock.rb
Capistrano.Caplock.remote_file_differs?
def remote_file_differs?(full_path, content) !remote_file_exists?(full_path) || remote_file_exists?(full_path) && !remote_file_content_same_as?(full_path, content) end
ruby
def remote_file_differs?(full_path, content) !remote_file_exists?(full_path) || remote_file_exists?(full_path) && !remote_file_content_same_as?(full_path, content) end
[ "def", "remote_file_differs?", "(", "full_path", ",", "content", ")", "!", "remote_file_exists?", "(", "full_path", ")", "||", "remote_file_exists?", "(", "full_path", ")", "&&", "!", "remote_file_content_same_as?", "(", "full_path", ",", "content", ")", "end" ]
Returns Boolean indicating whether the remote file is present and has the same contents as the String in +content+.
[ "Returns", "Boolean", "indicating", "whether", "the", "remote", "file", "is", "present", "and", "has", "the", "same", "contents", "as", "the", "String", "in", "+", "content", "+", "." ]
04525a983abe2e63210d7d605073fdd39c641f73
https://github.com/Druwerd/caplock/blob/04525a983abe2e63210d7d605073fdd39c641f73/lib/caplock.rb#L33-L35
18,199
enkessler/cuke_modeler
lib/cuke_modeler/adapters/gherkin_6_adapter.rb
CukeModeler.Gherkin6Adapter.adapt_tag!
def adapt_tag!(parsed_tag) # Saving off the original data parsed_tag['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_tag)) parsed_tag['name'] = parsed_tag.delete(:name) parsed_tag['line'] = parsed_tag.delete(:location)[:line] end
ruby
def adapt_tag!(parsed_tag) # Saving off the original data parsed_tag['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_tag)) parsed_tag['name'] = parsed_tag.delete(:name) parsed_tag['line'] = parsed_tag.delete(:location)[:line] end
[ "def", "adapt_tag!", "(", "parsed_tag", ")", "# Saving off the original data", "parsed_tag", "[", "'cuke_modeler_parsing_data'", "]", "=", "Marshal", "::", "load", "(", "Marshal", ".", "dump", "(", "parsed_tag", ")", ")", "parsed_tag", "[", "'name'", "]", "=", "parsed_tag", ".", "delete", "(", ":name", ")", "parsed_tag", "[", "'line'", "]", "=", "parsed_tag", ".", "delete", "(", ":location", ")", "[", ":line", "]", "end" ]
Adapts the AST sub-tree that is rooted at the given tag node.
[ "Adapts", "the", "AST", "sub", "-", "tree", "that", "is", "rooted", "at", "the", "given", "tag", "node", "." ]
6c4c05a719741d7fdaad218432bfa76eaa47b0cb
https://github.com/enkessler/cuke_modeler/blob/6c4c05a719741d7fdaad218432bfa76eaa47b0cb/lib/cuke_modeler/adapters/gherkin_6_adapter.rb#L171-L177